1

Why does this not work?

class MyClass<GenericClass> {
  GenericClass myInstance;

  MyClass() {
    myInstance = new GenericClass();
  }
}

I get a "cannot instantiate" COMPILE time error message on the 'new'. Even if I make sure that there is a parameterless constructor.


Follow up: is there a preferred way to address this? Or am I forced to do this (assuming I have added the setMyInstance() method to MyClass<>

class Other {
...
...
}

MyClass<Other> mine = new MyClass<Other>();
mine.setMyInstance(new Other());

Which is not great because I am forced to reveal the implementation of MyClass outside of it.

What's the better way to handle it?

pitosalas
  • 10,286
  • 12
  • 72
  • 120

2 Answers2

2

Two words: type erasure.

The concrete value of the type parameter is not available at runtime, so there is no way to know what type to instantiate. Further, there is no guarantee that there is a callable no-arg constructor to use.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 3
    That's the point. Because you won't be able to access the type parameter at runtime, you're forbidden from writing this code at compile time. – Louis Wasserman Feb 08 '12 at 00:57
0

Type erasure strikes again!

Jeffrey
  • 44,417
  • 8
  • 90
  • 141