【发布时间】:2019-03-03 08:44:09
【问题描述】:
此代码崩溃:
public class MyClass {
public static void main(String args[]) {
Person person = new Person();
person.selectMe();
}
}
class Entity {}
interface EntityNameable<T extends Entity> {
default String getSomething() {
return "";
}
}
interface EntityNameableSelectable<T extends EntityNameable> {
default String selectMe() {
return ((EntityNameable) this).getSomething();
}
}
class Person extends Entity implements EntityNameableSelectable {
}
这段代码可以通过复制粘贴到https://www.jdoodle.com/online-java-compiler来执行
Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to EntityNameable
at EntityNameableSelectable.selectMe(MyClass.java:18)
at MyClass.main(MyClass.java:4)
它崩溃是因为 person 不能转换为 EntityNameable。为什么不? person 始终是 Entity、EntityNamable 和 EntityNameableSelectable 对吧?
我也想知道为什么我需要将它转换为EntityNameable 来调用方法getSomething,因为每个实现类都应该有那个方法。为什么需要演员表?它必须与崩溃有关...
【问题讨论】:
标签: java inheritance interface java-8 default-method