我有以下第一个泛型类及其接口(interface):
public interface Generic1Interface<E extends Comparable> {
..
}
public class Generic1 <E extends Comparable> implements
Generic1Interface<E> {
.. //implementation of Doubly linked list using Node objects
}
第二个泛型类及其接口(interface):
public interface Generic2Interface<E extends Comparable> {
..
}
public class Generic2 <E extends Comparable> implements
Generic22Interface<E> {
Generic1Interface<E> list;
//so nothing here but a reference to an object of type Generic1Interface<E>
Generic2() {
list = new Generic1();
}
假设我们正在研究第二个类中的一个方法,并且我们尝试实例化第二个类的新实例,并将其命名为“result”,然后尝试访问其 Generic2 实例,它将给出错误:
public Generic2Interface<E> union (E a, E b) {
Generic2Interface<E> result = new Generic2();
**result.list** = ....;
result.list 将给出错误:“列表无法解析或不是字段”。我认为必须有一个解决方法来实例化泛型类中的泛型类。 谢谢。
编辑:我需要符合每个实现的类中的接口(interface)。正如您所看到的,方法 union 必须返回 Generic2Interface 类型的对象,这就是我这样声明结果的原因。
最佳答案
您需要将结果强制转换为 Generic2
类型。这有效:
System.out.println(((Generic2)result).list);
或者这个:
Generic2<E> result = new Generic2();
System.err.println(result.list);
关于java - 在泛型类中实例化泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46789126/