Java Generics Call Constructor

Jan-Benedikt Jagusch :

Let's assume I have four classes: Car, Convertible, PickupTruck and CarManufacturer.

Car is the abstract class that Convertible and PickupTruck inherit from:

public abstract class Car {
    private String name;
    private String colour;

    //Constructor
}

Convertible and PickupTruck both have parameterless constructors:

public class Convertible extends Car {
    private boolean roofUnfolded;

    public Convertible() {
        super("Convertible", "Red");
        this.roofUnfolded = false;
    }
}

public class PickupTruck extends Car {
    private double capacity;

    public PickupTruck() {
        super("Pickup Truck", "Black");
        this.capacity = 100;
    }
}

CarManufacturer stores a List of either Convertibles or PickupTrucks.

public class CarManufacturer <T extends Car>{
    private List<T> carsProduced = new LinkedList<>();
}

How can I implement a function produceCar() that calls the parameterless constructor and adds the object to the list? I tried:

public void produceCar(){
    this.carsProduced.add(new T());
}

Returning the error: Type parameter 'T' cannot be instantiated directly

Jan-Benedikt Jagusch :

The same issues was solved here: https://stackoverflow.com/a/36315051/7380270

With regards to the problem, this works:

public class CarManufacturer <T extends Car> {
    private Supplier<T> carType;
    private List<T> carsProduced = new LinkedList<>();

    public CarManufacturer(Supplier<T> carType) {
        this.carType = carType;
    }

    public void produceCar() {
        this.carsProduced.add(carType.get());
    }

}

public class Main {
    public static void main(String[] args) {
        CarManufacturer<Convertible> convertibleCarManufacturer = new CarManufacturer<>(Convertible::new);
        convertibleCarManufacturer.produceCar();
    }
}

Guess you like

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