Java Inheritance: Restrict List to Subclass Objects

Jan-Benedikt Jagusch :

Let's assume I have 3 classes: Car, Convertible and Garage.

Car:

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

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

Convertible inherits from 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;
    }
}

Garage stores a list of Cars:

public class Garage {
    private int capacity;
    private List<Car> cars = new LinkedList<Car>();

    //Setter for capacity
}

How could I create a subclass of Garage called ConvertibleGarage that can only store Convertibles?

Chris :

You could use a little bit of generics:

public class Garage<T extends Convertible> {
    private int capacity;
    private List<T> cars = new LinkedList<T>();

    public Garage(int capacity) {
        this.capacity = capacity;
    }
}

This means when you instantiate a Garage you now have to include a parameter type that is a Convertible or child of it.

Garage<Convertible> cGarage = new Garage<>();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=434161&siteId=1