java如何调用父重写方法
我有两个班,父母和孩子。我从子类调用父重写方法(show)。在父类中,我调用了另一个方法(display),但由于调用了哪个子方法,该方法也被重写。 我想从show方法调用父方法display
public class Parent {
public void show()
{
System.out.println("Show of parent ");
this.display();
}
public void display()
{
System.out.println("Display of parent");
}
}
public class Child extends Parent{
public void show()
{
System.out.println("Show of child ");
super.show();
}
public void display()
{
System.out.println("Display of child");
}
public static void main(String[] args) {
Parent obj = new Child();
obj.show();
}
}
输出:
Show of child
Show of parent
Display of child
需要:
Show of child
Show of parent
Display of parent
即。
我想从同一个类的show()
方法调用父类的display()
方法
# 1 楼答案
解释:
这与隐藏方法有关。隐藏方法的规则与添加}方法打印“显示父对象”,然后调用{}。由于
static
关键字覆盖的规则相同。使用static
关键字,可以隐藏display()
方法。 所以当obj调用方法show()
时,计算机会这样运行: 我有对象Child
和Parent
引用(它可以是Child
引用,在本例中输出仍然相同)。Child
对象有show()
打印“子对象的显示”,然后调用Parent
类的show()
方法。Parent
{display()
是static
,Parent
只知道自己的display()
方法,因此打印“父项显示”虽然,这是一个选项,但最好不要使用它,因为它可能会导致混乱和难以阅读的代码