问题描述
我知道在方法覆盖的情况下会发生多态。
但是我对下面的内容感到有些困惑。
I know polymorphism happens in the case of method overriding.But I am a little confused about the below.
class A {
public void hi() {
System.out.println("A "+this.getClass().getName());
}
}
class B extends A {
public void bye() {
System.out.println("B "+this.getClass().getName());
}
}
class Ideone {
public static void main (String[] args) throws java.lang.Exception {
A a = new B();
a.hi();
a.bye();
}
}
输出:
Main.java:35: error: cannot find symbol
a.bye();
^
symbol: method bye()
location: variable a of type A
1 error
为什么会出现编译时错误?
Why does this give a compile time error?
在 a = new B()
, B
类对象是在运行时创建的,所以 a
'一个指向一个的引用变量对象类型 B
。
In a = new B()
, the B
class object is created at runtime, so a
's a reference variable pointing to an object of type B
.
现在如果我们调用 B
的类方法 bye()
,为什么它是编译器时间错误?
Now if we call B
's class method bye()
, why it is a compiler time error?
推荐答案
变量 a
的声明类型是A.编译器不知道(也不应该知道)它在运行时的具体类型是什么。它只知道它是A,并且A中没有 bye()
方法。
The declared type of the variable a
is A. The compiler doesn't know (and shouldn't know) what its concrete type at runtime is B. All it knows is that it's a A, and that there is no bye()
method in A.
整点做法
A a = new B();
而不是
B a = new B();
要清楚地说a是A,并且可以有任何具体类型,只要conrete类型扩展A.你必须能够,如果你以后找到更好的A实现,只需将该行更改为
is to clearly say that a is a A, and could have any concrete type, as long as the conrete type extends A. You must be able, if you find a better implementation of A later, to just change that line to
A a = new BetterImplementation();
A a = new BetterImplementation();
并编译代码。
这篇关于为什么在使用超类引用调用子类方法时会出现编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!