Jan*_*sch 12 java generics collections inheritance list
我们假设我有3个类:汽车,敞篷车和车库.
汽车:
public class Car {
private String name;
private String color;
public Car(String name, String color) {
this.name = name;
this.color = color;
}
//Getters
}
Run Code Online (Sandbox Code Playgroud)
敞篷继承自汽车:
public class Convertible extends Car{
private boolean roof;
public Convertible(String name, String color, boolean roof) {
super(name, color);
this.roof = roof;
}
public boolean isRoof() {
return roof;
}
}
Run Code Online (Sandbox Code Playgroud)
车库存储汽车列表:
public class Garage {
private int capacity;
private List<Car> cars = new LinkedList<Car>();
//Setter for capacity
}
Run Code Online (Sandbox Code Playgroud)
我怎么能创建一个只能存储Convertibles 的Garage被调用的子类ConvertibleGarage?
你可以使用一些泛型:
public class Garage<T extends Convertible> {
private int capacity;
private List<T> cars = new LinkedList<T>();
public Garage(int capacity) {
this.capacity = capacity;
}
}
Run Code Online (Sandbox Code Playgroud)
这意味着当您实例化a时,Garage您现在必须包含一个可转换的子参数类型或它的子类.
Garage<Convertible> cGarage = new Garage<>();
Run Code Online (Sandbox Code Playgroud)
泛型将在这里提供帮助.
使Garage类通用Garage<T extends Car>,其中a T是可以存储的汽车类型.将cars列表重写为通用视图List<T>.
然后,a Garage<Convertible>将成为您的"ConvertibleGarage".