为什么会出现以下输出/错误?
public class A1 {
public void bar() {
System.out.println("A1 bar");
}
public static void main(String[] args) {
List<A1> list = new ArrayList<>();
list.add(new B());
/* add the missing lines here*/
}
}
public interface A2 {
void foo(List<A1> list, int idx);
}
public class B extends A1 implements A2 {
public void foo(List<A1> list, int idx) {
A1 a1 = list.get(idx);
if (a1 instanceof B) {
System.out.println("It's a B!");
} else {
a1.bar();
}
}
public void bar() {
System.out.println("B bar");
}
}
1) 在main中添加以下行时:
list.add(new A1());
A2 a=(A2) list.get(0);
a.foo.(list,1);
为什么没有编译错误,因为动态类型不能是接口(interface)? (输出是“A1 bar”)。
2) 为什么下面几行会导致“运行时错误”而不是“编译错误”?
list.add(new A1());
A2 a = (A2) list.get(1);
a.foo(list, 0);
3) 对于以下类层次结构,得出以下结论是否正确:
Interface Animal {...}
class Dog implements Animals {...}
class Poodle extends Dog {...}
class Labrador extends Dog {...}
因为动态类型是一个接口(interface),下面这行不能编译?
Animal animal=(Animal) poodle;
最佳答案
Why there isn't compilation error, since dynamic type can't be interface? (the out put is "A1 bar").
某些东西可以同时是 A1 和 A2,例如 B。那么为什么编译器仅仅因为它不在那种(运行时)情况下就应该显示错误? list.get(0);
将返回 A1,true,但编译器没有机会知道它是否也将是 A2。
2) Why the following lines lead to "run time error" but not to "compilation error"?
两种可能性,取决于您添加它的位置。要么你得到一个 IndexOutOfBoundsException,因为编译器不计算列表的大小。为什么要这样?编译器应该做什么是有限制的。在这种情况下,可能可以在编译时计算列表大小——但在许多其他情况下则不能,因此编译器的工作不是检查类似的东西。
或者您收到 ClassCastException,因为您正在取回 A1 对象并尝试将其转换为 A2。这可以工作,例如,如果您的 A1 对象也是 B。但在您的情况下,它不是,只是一个简单的普通 A1 对象,它不是 A2。因此你不能把它合二为一。例如,Dog 可能是 FemaleDog,但不一定是。如果您尝试将非 FemaleDog 转换为 FemaleDog,则会出现异常。
Animal animal=(Animal) poodle;
...工作得很好,因为 Poodle 是一只狗,它是一种动物,因此 Poodle 是一种动物。
关于java - 如何使用带接口(interface)的类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32251013/