Search code examples
javaooptype-parameter

Instantiating a Type Parameter Without Passing an Object


My question is very similar to this question. I want to be able to instantiate an object of the type parameter type, but also without needing to pass in a "factory". I really need to be contained all in the one class.

public class myClass<E> {
    E someObject;

    public myClass(){
         someObject = new E();
    }
}

Previous solutions required the constructor of myClass to be changed to have a factory parameter, and then to call the constructor of that, but for my purposes I don't want to modify any calls to myClass from the outside.


Solution

  • The problem is that you don't know what E is, nor how to construct it. It could be any type (it's universally quantified). You need to supply evidence that, whatever E is, it can really be constructed. A "factory" of a given type serves as a kind of witness to the fact that it can.

    Think about this for a second: What if I pass Void as the parameter E? How would you go about constructing a value of type Void?

    Being able to construct E for all E would be like creating something out of nothing. It's a logical impossibility. ∀E. E is an uninhabited set.

    What you really want is either for E to have a bound, or to pass a constructor (factory) as a witness of the fact that E is in the set of constructable objects.