Reputation: 75
I have the following first generic class and its interface:
public interface Generic1Interface<E extends Comparable> {
..
}
public class Generic1 <E extends Comparable> implements
Generic1Interface<E> {
.. //implementation of Doubly linked list using Node objects
}
And the second generic class and its 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();
}
Suppose we're working on a method inside the second class, and we try to instantiate a new instance of the second class, and name it "result", then try to access its Generic2 instance, it will give an error:
public Generic2Interface<E> union (E a, E b) {
Generic2Interface<E> result = new Generic2();
**result.list** = ....;
result.list will give an error: "list cannot be resolved or is not a field". I think there must be a workaround to instantiate a generic class in a generic class. Thanks.
EDIT: I need to conform to the interfaces in each implemented class. So as you can see the method union has to return object of type Generic2Interface that's why I declare result like this.
Upvotes: 1
Views: 106
Reputation: 4956
You need a cast for result to Generic2
type. This works:
System.out.println(((Generic2)result).list);
Or this:
Generic2<E> result = new Generic2();
System.err.println(result.list);
Upvotes: 1