为什么不能使用引用子类型实例的父类型引用来调用子类方法? [英] why can't I call a subclass method using a reference of a parent type that refers to an instance of a sub-type?
本文介绍了为什么不能使用引用子类型实例的父类型引用来调用子类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Java,同时试图了解继承.我不知道为什么要执行子类walk()的重写方法,而不执行其他xyz()方法.
I am Learning Java, while trying to understand inheritance. I couldn't figure out why the overridden method at the subclass walk() executed but not the other xyz() method.
class Person{
public void walk() { System.out.println("walking like a person "); }
}
public class Soldier extends Person{
@override
public void walk() { System.out.println("marching like a soldier "); }
public void xyz() { System.out.println("xyzng like a pro"); }
public static void main(String[] args) {
Person sp = new Soldier();
sp.walk();
sp.xyz();
}
}
这是我的问题,如果下面的方法调用工作正常并调用Soldier方法walk,
Here is my question, if the following method call works fine and calls the Soldier method walk,
sp.walk();
为什么编译器抱怨此调用?
why the compiler complain about the this call?
sp.xyz();
推荐答案
在编译时,父类引用"sp"只能看到其中的方法.如果您想以((Soldier)sp).xyz()
At the compile time parent class reference 'sp' can only see method inside it. if you want to access as ((Soldier) sp).xyz()
这篇关于为什么不能使用引用子类型实例的父类型引用来调用子类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文