calling parent class method from child class object in java

ran*_*mar 24 java

I have a parent class which have a method, in child class i have override that parent class method . In a third class i make a object of child and by using that object i want call method of parent class.Is it possible to call that parent class method ? If yes then how?

Please reply

Erk*_*lat 24

如果在其子项中覆盖父方法,则子对象将始终使用重写的版本.但; 您可以使用关键字在子方法体内super调用父方法.

public class PolyTest{
    public static void main(String args[]){
        new Child().foo();
    }

}
class Parent{
    public void foo(){
        System.out.println("I'm the parent.");
    }
}

class Child extends Parent{
    @Override
    public void foo(){
        //super.foo();
        System.out.println("I'm the child.");
    }
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

我是孩子.

取消注释注释行,它将打印:

我是父母.

我是孩子.

你应该寻找多态性的概念.


Sag*_*r V 5

在子类的重写方法中使用关键字super可以使用父类方法。但是,您只能在覆盖的方法中使用关键字。下面的示例将有所帮助。

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}
Run Code Online (Sandbox Code Playgroud)

addChild类中的方法调用super.add以重用加法逻辑。