Why is it impossible to use generic type for variable when instantiating object with concrete type?

class A{}
class B extends A {}
class C extends B {}
class D<C> {
    C c = new A(); // COMPILER ERROR
}

After type erasure code becomes:

class D {
    Object c = new A();
}

So, what's the problem here?

Jon Skeet
people
quotationmark

So, what's the problem here?

The first problem is that within D<C>, C refers to the type parameter called, C, not the class C that extends B. Next, even ignoring generics,

C c = new A(); // Invalid

... wouldn't compile... instead, you'd normally have:

A a = new C(); // Normally fine - but not if C is a type parameter!

Suppose you tried using:

D<String> d = new D<String>();

Then you're effectively asking the compiler to consider this line to be valid:

String c = new A();

That's clearly broken.

people

See more on this question at Stackoverflow