-5

Could you please help me to understand the generic concept here.

// Can't create an instance of T.
class Gen<T> {
  T ob;

  Gen() {
    ob = new T(); // Illegal!!!
  }

  public static void main() {

    Gen<Integer> genobj = new Gen<Integer>(); //Error
  }
}

When your Java code is compiled, all generic type information is removed (erased). This means replacing type parameters with their bound type, which is Object if no explicit bound is specified, and then applying the appropriate casts (as determined by the type arguments) to maintain type compatibility with the types specified by the type arguments. The compiler also enforces this type compatibility.

My question:-Why java complier is throwing error here ? Bevause after complitaion .

Thanks

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
alakhya
  • 35
  • 1
  • 7
  • After compilation, the type `T` is erased, so program won't know what type you are trying to instantiate. – khelwood Jun 02 '16 at 12:32
  • Please correct me if i am wrong.'T' is replaced with Java.lang.Object – alakhya Jun 02 '16 at 12:33
  • Gen genobj=new Gen() after complilation it would be Gen genobj=new Gen() – alakhya Jun 02 '16 at 12:34
  • T is not replaced with type Object. T is replaced by whatever you program it to accept by providing a type when you call it Gen gen = new Gen();. If you want to create a new "T" type then you must use T.newInstances(); [Instantiating generics type in java](http://stackoverflow.com/questions/2434041/instantiating-generics-type-in-java) What are you trying to do, your code doesn't make sense. – Mr00Anderson Jun 02 '16 at 12:41

1 Answers1

3

There are a few ways that may work out here:

From a logical POV:
It's not even guaranteed that whatever template-parameter T you use has a default-constructor. Which obviously offers the problem of how to handle the absence of a default-constructor. Possible solutions would be to produce a runtime-error, compile-time error or disallow any T that doesn't provide a default-constructor. The latter would obviously break the template-definition, which allows any T. And the runtime-error would complicate things quite a bit and yield the same problem as mentioned above. Remains preventing this behavior in the first place and throwing a compile-time error.

From a internal view:
Let's assume we could use the provided code. Then how would it work? Due to erasure, new T() would produce an Object. But what if T is Integer? Well, we're screwed. An Object is not an Integer, so we'll get a plain class-cast exception.

So in summary: allowing the above to compile wouldn't work from a practical POV and in addition break the current definition of generics in java.