Java Inheritance: Restrict List to Subclass Objects

Viewed 1703

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?

4 Answers
Related