【发布时间】:2017-01-24 21:23:05
【问题描述】:
我有一个问题,我有一些班级说
public class Foo {
public Foo() {
// Do stuff
}
public void generalMethod() {
//to general stuff
}
}
public class Bar extends Foo {
public Bar() {
//do stuff
}
public void uniqueMethod() {
//do stuff
}
}
public class Driver() {
public static void main(String[] args) {
Foo test = new Bar();
test.uniqueMethod(); //this causes an error
}
}
所以我收到一条错误消息,指出方法 uniqueMethod() 未为 Foo 定义,但是当我将分配更改为 Bar test = new Bar(); 时,问题就消失了。我不明白,因为它应该适用于Foo test = new Bar();
有人可以提出这个错误发生的原因吗?
提前谢谢你。
【问题讨论】:
-
为什么它应该与
Foo一起使用?该类中没有这样的方法。 -
因为 Foo 是父类,JVM 不应该查看 uniqueMethod() 的子类,因为它不在父类 (Foo) 中
-
JVM 在这里无关紧要。编译器在工作,他只查看定义的变量类型。多态(你的意思)发生在运行时,而不是编译时。
-
它适用于声明的类型,即您在变量名之前定义的类型,而不是在运行时分配给它的类型。
标签: java inheritance polymorphism