Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance: Restrict List to Subclass Objects

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?

like image 324
Jan-Benedikt Jagusch Avatar asked Jul 18 '17 13:07

Jan-Benedikt Jagusch


Video Answer


1 Answers

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<>();
like image 74
Chris Avatar answered Oct 18 '22 19:10

Chris