gpt4 book ai didi

Java不能用不同的参数继承

转载 作者:行者123 更新时间:2023-11-30 05:44:18 25 4
gpt4 key购买 nike

我在实际继承接口(interface)时遇到了麻烦。我总是以错误结束

error: NameableContainer cannot be inherited with different arguments: < Friend> and <>

我有以下接口(interface):

public interface Nameable

public interface Name

public interface Friend extends Nameable

public interface NameableContainer<T extends Nameable> {
void add(Name name, Name prevName);

void remove(Nameable nameable);

T findByName(Name name);
}

public interface FriendContainer extends NameableContainer<Friend>

我还有一个继承 NameableContainer 的抽象类。

public abstract class NameableMap implements NameableContainer {
public void add(Name name, Name prevName) { /* do stuff*/ }

public void remove(Nameable nameable) { /* do stuff*/ }

public Nameable findByName(Name name) { /* do stuff*/ }
}

最后,尝试将这些放在一起

public class Friends extends NameableMap implements FriendContainer

我错过了什么?

最佳答案

当您说时,您正在使用原始类型

public abstract class NameableMap implements NameableContainer

这会导致编译器中的所有内容都失效;原始类型是一个错误,除非您的代码最初是为 java 1.4 或更早版本编写的。当您实现指定类型参数的接口(interface)时,您要么需要提供具体类型,要么如果尚不知道,则可以引入另一个类型参数并将其传递给父类(super class)型。

参见: What is a raw type and why shouldn't we use it?

因此,您在实现 NameableContainer 时指定了一个可变泛型类型参数(因为您还不知 Prop 体类型,因为 NameableMap 也应该适用于所有 Nameable。

public abstract class NameableMap<T extends Nameable> implements NameableContainer<T>
// ^^^^^^^^^^^^^^^^^^^^ ^^^

关于Java不能用不同的参数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55113826/

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