Reputation: 51
Let's assume I have a class A that can be extended. Within that Class A I have a List List<A>
. So this class will contain a list with elements A. Now If I subclass this class B extends A, I want class B to have the same member List<B>
, ie the same list but this type containing items of type B. Is this possible using generics ? I can see something like A <T extends A>
, while declaring List<T>
, but I don't like as the information about the class type are already there. Is there another better solution ? Example below:
public class A {
List<A> list = new ArrayList<A>();
}
public class B extends A {
}
I want list to have the generic type of B in class B.
Upvotes: 0
Views: 446
Reputation: 9505
You can use extends
keyword in generic.
For example:
public class A {
protected List<? extends A> list;
public A() {
list = new ArrayList<A>();
}
public <T extends A> List<T> getList() {
return (List<T>) list;
}
public void setList(List<A> list) {
this.list = list;
}
}
public class B extends A {
public B() {
list = new ArrayList<B>();
}
public static void main(String[] args) {
A a = new A();
a.getList().add(new A());
B b = new B();
b.getList().add(new B());
}
}
Upvotes: 0
Reputation: 18435
If you want to put the behaviour in the super class, then you're going to have to tell the super class what type of class the subclass is. This can be done by adding a generic type to the super.
public class A<E> {
protected List<E> items;
public A() {
this.items = new ArrayList<E>();
}
}
public class B extends A<B> {
public static void main(String[] args) {
B b = new B();
b.items.add(b);
}
}
Upvotes: 2