【发布时间】:2014-04-03 19:18:00
【问题描述】:
我有以下场景。
public class Fruit {
public Fruit() {
System.out.println("Fruit Constructor");
}
public String callSuperApple() {
return "super fruit";
}
}
public class Apple extends Fruit{
private String color;
public String callSuperApple() {
return "super fruit";
}
}
还有一些第三类:
public class SomeClass{
private String color;
public String callSuperApple() {
return "fruit";
}
}
现在主要方法的实现:
public class MainClass{
public static void main(String[] args) {
Fruit fruit= new Fruit ();
String string = (String)((Apple)fruit).callSuperApple();//line 3
System.out.println(string);
}
}
这里我们在运行时有异常但没有编译时错误。
但是当第3行改为
String string = (String)((SomeClass)fruit).callSuperApple();
它会引发编译时错误。同样callSuperApple()方法在SomeClass和Fruit中实现。
现在,Apple 是Fruit 的一种类型,但我们可以将fruit 类型转换为Apple。将Apple 类型转换为Fruit 是有道理的,但反过来不行。为什么在编译时允许这样做,而 SomeClass 仅在编译时被捕获?
【问题讨论】:
标签: java inheritance compilation compiler-errors