假设我有3个类(class):汽车,敞篷车和车库。

车:

public class Car {
    private String name;
    private String color;

    public Car(String name, String color) {
        this.name = name;
        this.color = color;
    }
    //Getters
}

敞篷车继承自Car:
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;
    }
}

车库存储汽车列表:
public class Garage {
    private int capacity;
    private List<Car> cars = new LinkedList<Car>();

    //Setter for capacity
}

如何创建只能存储可转换货币的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;
    }
}

这意味着当实例化Garage时,现在必须包括一个Convertible或它的子代的参数类型。
Garage<Convertible> cGarage = new Garage<>();

09-19 15:17