4
public class MyClass<T> extends T {...}

The above declaration will fail to compile with the error:

error: unexpected type
class MyClass<T> extends T {}
                         ^
  required: class
  found:    type parameter T
  where T is a type-variable:
    T declared in class MyClass

I can't really think of a reason for this to happen, so I am wondering if someone can shed some light on why it is that Java won't let you inherit from a generic type-variable.

Jorn Vernee
  • 26,917
  • 3
  • 67
  • 80

4 Answers4

2

Java has quite a lot of language restrictions unlike C++ for example. What you want is not possible for many reasons listed in the comments (T might be final or have abstract methods). However, you are allowed to extend from a supertype having the generic type parameter:

public class MyClass<T> extends AnotherClass<T>

You might find the following alternative interesting:

public class MyClass<T extends AnotherClass> extends AnotherClass

What you want to do does make not much sense.

Nikolas Charalambidis
  • 29,749
  • 7
  • 67
  • 124
2

The most obvious reason I can think of isn't even about type-erasure; it is the fact that when you make A a subclass of B, the Java compiler needs to know what constructors B has. If a class does not have a no-arguments constructor, then its sub-classes must call one of its defined constructors. But when you declare

public class MyClass<T> extends T {...}

It is absolutely impossible for the compiler to know what the super constructors are, since T is not fixed at compile-time (that's the whole point of generics after all), which is a situation that cannot be allowed in Java.

Leo Aso
  • 9,400
  • 3
  • 16
  • 40
1

Your question is not so weird as it may look like :) Consider how would you deal with following:

  1. Suppose your real class for T has a single constructor with 3 parameters. How would you implement the constructor of inherited class, if you don't know how to call the super constructor?

  2. Suppose your real class for T has public final methods and you have defined methods with the same signature in the inherited class. What method would your object have? You cannot resolve such conflict.

mentallurg
  • 4,271
  • 5
  • 22
  • 32
0

Simple deductions based on your question.

T is a type.

MyClass extends T - MyClass is enhanced version of T.

MyClass < T> extends T - MyClass is enhanced T, but only for Type T.

there is no reason to state ' I extend T but only for type T'.

If you extend T, MyClass is already a Type of T & definitely not some X,Y or Z.

Generics are needed if you want to ensure Type safety, if you extend it is already type safe.

Sundar Rajan
  • 396
  • 2
  • 18