我希望实现如下所示的不可变列表接口(interface):
public interface InterfList<T> extends Iterable<T> {
public InterfList<T> append(T t);
//More abstract methods follow
}
当我让 netbeans 为我实现接口(interface)时,出现了:
public class MyList implements InterfList {
private Object value;
@Override
public InterfList append(Object t) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
但是,我想保留模板,以便只接受正确类型的对象。例如:
public class MyList<T> implements InterfList {
private T value;
@Override
public InterfList<T> append(T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
第一种方法允许将任何类型的对象存储在列表中,使其变得非常困惑。
但是,第一种方法在 netbeans 中被标记为错误:
MyList
is not abstract and does not implement methodappend(object)
inInterfList
最佳答案
你应该这样做:
public class MyList<T> implements InterfList<T> {
private T value;
@Override
public InterfList<T> append(T t) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
您想要实现 InterfList<T>
.
自从您实现InterfList
以来没有任何类型参数,您正在实现 InterfList<Object>
,这会导致 append
错误方法,需要 T
而不是Object
。您想要实现InterfList<T>
.
关于java - 如何实现使用模板的界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24099276/