我来自以下代码:
class Animal{
public void eat() throws Exception {}
}
class Dog extends Animal{
public void eat(){} //no exception thrown
public static void main(String[] args){
Animal a = new Dog();
Dog d = new Dog();
d.eat(); //ok
a.eat(); //does not compile!..(1)
}
}
Run Code Online (Sandbox Code Playgroud)
这里,(1)即使在运行时也不会编译Dog的eat()方法将被调用.为什么会这样?Java支持这个的原因是什么?这不应该是一个bug吗?
因为您使用Animal引用来引用a Dog.而签名Animal.eat包括Exception.编译器知道a Dog是一种Animal,但是一旦你使用了Animal引用,它就不知道它Dog直到运行时.
换一种方式,所有的Dog(S)是Animal(一个或多个),但不是所有的Animal(S)是Dog(S).
编辑
你可以添加一个演员
((Dog) a).eat(); //would compile
Run Code Online (Sandbox Code Playgroud)
在运行时,如果a实际上不是,那将失败Dog.
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |