gpt4 book ai didi

java - 在另一个默认方法中从其他接口(interface)调用默认方法

转载 作者:行者123 更新时间:2023-12-01 17:48:53 24 4
gpt4 key购买 nike

此代码崩溃:

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,因为每个实现类都应该具有该方法。为什么需要 Actor 阵容?它必须与崩溃有关......

最佳答案

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 不扩展该接口(interface),因此不会继承任何方法。

您可能希望 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 Person extends Entity implements EntityNameableSelectable<Person> {}

关于java - 在另一个默认方法中从其他接口(interface)调用默认方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52536910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com