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