从java中的子类对象调用父类方法 [英] calling parent class method from child class object in 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?
请回复
推荐答案
如果覆盖子对象中的父方法,子对象将始终使用被重写的版本。但;您可以使用关键字 super
来调用父方法在子方法体内。
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super
to call the parent method, inside the body of the child method.
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.");
}
}
这将打印:
我是孩子。
I'm the child.
取消注释评论行及其将打印:
Uncomment the commented line and it would print:
我是父母。
I'm the parent.
我是孩子。
你应该寻找多态性的概念。
You should look for the concept of Polymorphism.
这篇关于从java中的子类对象调用父类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!