在另一个默认方法中从其他接口调用默认方法

Call default method from other interface in another default method

此代码崩溃:

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 总是 EntityEntityNamableEntityNameableSelectable,对吗?

我也想知道为什么我需要将其转换为 EntityNameable 以调用方法 getSomething,因为每个实现 class 都应该有该方法。为什么需要演员阵容?它必须对崩溃做些什么...

I am also wondering why I need to cast this to EntityNameable to call method getSomething, as every implementing class should have that method.

EntityNameableSelectable 不是 EntityNameableEntityNameableSelectable 不扩展该接口,因此不继承任何方法。

可能,您希望 EntityNameableSelectable 扩展 EntityNameable,这样您就可以调用 getSomething().

interface EntityNameableSelectable<T extends Entity> extends EntityNameable<T> {
    default String selectMe() {
        return getSomething();
    }
}

A Person is always an Entity, EntityNamable and EntityNameableSelectable, right?

仅当 EntityNameableSelectable 扩展 EntityNameablePerson 实现 EntityNameable.

如果你像我上面提到的那样定义了 EntityNameableSelectable,那么 Person class 看起来像:

class Person extends Entity implements EntityNameableSelectable<Person> {}

A Person is always an Entity, EntityNamable and EntityNameableSelectable right?

A Person 扩展了 Entity 并实现了 EntityNameableSelectable,但它没有实现 EntityNameable,没有。

我不知道你到底想做什么,但我怀疑 <T extends EntityNameable> 没有按照你的意愿去做。尝试让 EntityNameableSelectable 扩展 EntityNameable

interface EntityNameableSelectable extends EntityNameable {
  default String selectMe() { 
    return getSomething();
  } 
}

同样,使 EntityNameable 具有通用 T 参数可能也不正确。在您的示例代码中,T 没有执行任何操作,因此您可以将其删除。

interface EntityNameable {
  default String getSomething() {
    return "";
  } 
}