我們假設我有四個類:Car
,Convertible
,PickupTruck
和CarManufacturer
。Java泛型調用構造函數
Car
是抽象類,Convertible
和PickupTruck
繼承:
public abstract class Car {
private String name;
private String colour;
//Constructor
}
Convertible
和PickupTruck
都有參數構造函數:
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
商店要麼Convertibles
或PickupTrucks
的名單。
public class CarManufacturer <T extends Car>{
private List<T> carsProduced = new LinkedList<>();
}
我怎樣才能實現一個功能produceCar()
調用參數的構造函數和將對象添加到列表中?我想:
public void produceCar(){
this.carsProduced.add(new T());
}
返回錯誤:Type parameter 'T' cannot be instantiated directly
那麼有比使用反射更好的方法,但仍然是一個有效的答案。 – Flown