我正在尝试学习继承,并且遇到了这个问题。
这是代码:
import java.util.*;
class Parent
{
void show()
{
System.out.println("show from parent");
}
}
class Child extends Parent
{
public static void main(String s[])
{
Parent p=new Child();
p.show();
p.display();
}
void show()
{
System.out.println("show from child");
}
void display()
{
System.out.println("display from child");
}
}
错误是:
G:\javap>javac Child.java
Child.java:15: error: cannot find symbol
p.display();
^
symbol: method display()
location: variable p of type Parent
1 error
如果我能够访问 show()
那么为什么我无法访问 display()
知道 display()
是继承的,并且也存在于子类的类定义中。
最佳答案
您必须了解运行时类型和编译时类型之间的区别。
在运行时,您的变量p
保存对Child
实例的引用。因此,调用 show
方法将运行 Child#show
中的代码,因为这会覆盖方法 Parent#show
。
在编译时,编译器只能知道变量的声明类型。这是父级
。因此编译器只能允许访问Parent
类型的字段和方法,而不允许访问Child
类型的字段和方法。
display
方法根本没有在 Parent
中声明,因此会出现错误。
关于java - 为什么下面的代码会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36806938/