1

I am looking for alternatives to initialize a bounded generic type in Java. So far I have found 3 potential alternatives:

  1. Generics Factory
  2. Storing a class
  3. Built in Supplier interface

Initially, I thought that the generics factory would be more flexible, however as I saw the built-in supplier, I believe that this would be flexible and also easier to maintain. So I created the following example based on SomeContainer:
Car Example

Given that I have a CarPart class that has a subclass, and I have a car class (where T extends CarPart) that should hold a list of any type that extends the class CarPart. I am trying to see if there is an alternative to initialize any potential CarPart subclass and add to the carParts list (method addNewGenericCarPart()).

Here is the code:

public class Car<T extends CarPart> {
    private Supplier<T> carPartsSupplier;
    List<T> carParts;

    Car(Supplier<T> carPartsSupplier){
        this.carPartsSupplier=carPartsSupplier;
    }

    T createCarParts(){
        return carPartsSupplier.get();
    }

    public Car(List<T> carParts) {
        this.carParts = carParts;
    }
    void addNewGenericCarPart(){
//        TODO:Create a new generic Part Subclass
        Car<T> anythingExtendsCarParts=
                new T(T::new);//Error:Cannot resolve constructor 'T'

//        TODO:Add the new generic Part to carParts
        carParts.add(anythingExtendsCarParts);
    }
}
public class CarPart {
    String name="default";

    public CarPart() {
    }

    public CarPart(String name) {
        this.name = name;
    }

    void printCarParts(){
        System.out.println(name);
    }
}
public class CarPartSubclass extends CarPart {
    String subname;

    public CarPartSubclass() {
    }

    public CarPartSubclass(String name, String subname) {
        super(name);
        this.subname = subname;
    }

    void print(){
        System.out.println("This is a CarpartSubclass");
    }
}
public class Main {
    public static void main(String[] string) {
        List<CarPartSubclass> carPartsSubclassList=new ArrayList<>();
        carPartsSubclassList.add(new CarPartSubclass());

        Car<CarPartSubclass> car=new Car<CarPartSubclass>(carPartsSubclassList);
        car.addNewGenericCarPart();
    }
}

The above code results in the error

Cannot resolve constructor 'T' in the method addNewGenericCarPart() in the class Car.

  • Does anyone know if it is possible to create a workaround?
  • Or is there any alternative to be able to initialize a generic bounded class?
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DTK
  • 95
  • 1
  • 9

0 Answers0