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?
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<>();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With