I’m learning about Java. I would like to override the return type of ArrayList to subclass. Is it possible?
The compiler said that can override only the same type…
unit classes
import java.util.ArrayList;
abstract public class BaseUnit {
public BaseUnit() {
}
public abstract ArrayList<BaseElement> getList();
}
public class UnitA extends BaseUnit {
private ArrayList<ElementA> listA;
UnitA() {
super();
listA = new ArrayList<ElementA>();
listA.add(new ElementA());
}
public ArrayList<ElementA> getList() {
return listA;
}
}
element classes
public class BaseElement {
protected String name = "";
public BaseElement() {
}
public void sayName() {
System.out.println(name);
}
}
public class ElementA extends BaseElement {
public ElementA() {
name = "A";
}
}
main
public static void main() {
UnitA unitA = new UnitA();
unitA.getList().get(0).sayName();
}
>Solution :
The generics of the list in both types have to be the same. For what you want to do you basically have two options: Use the extends keyword, or make the type in the base class totally generic.
The first solution would look like this:
import java.util.ArrayList;
abstract public class BaseUnit {
public BaseUnit() {
}
public abstract ArrayList<? extends BaseElement> getList();
}
The second like this:
import java.util.ArrayList;
abstract public class BaseUnit<K> {
public BaseUnit() {
}
public abstract ArrayList<K> getList();
}
public class UnitA extends BaseUnit<ElementA> {
private ArrayList<ElementA> listA;
UnitA() {
super();
listA = new ArrayList<ElementA>();
listA.add(new ElementA());
}
public ArrayList<ElementA> getList() {
return listA;
}
}