Skeen
Skeen

Reputation: 4722

extending a class with a generics type, java

I'm trying to do the following in java:

public class ClassName<E> extends E

Doing this however, I'm getting a:

error: unexpected type

Is it simply the case, that java can't do this? - and if so, how will I achieve this effect? It works flawlessly in C++, with templates, alike:

template<typename E>
class ClassName: public E

What I'm really trying to achieve, is to be able to chain classes together this way, to achieve the effect of multiple inheritance in java.

Upvotes: 1

Views: 1759

Answers (4)

Thomas
Thomas

Reputation: 88707

In C++ templates have the effect of different classes being created at compile time, i.e. for every E you'd get a different version of ClassName.

In Java you have one class with that name and the generic type isn't used for much more than type checking at compile time. Thus Java can't let you extend from type E, since in that case the compiler would have to create multiple instances.

Additionally, generic types could be interfaces as well, and class ClassName extends Serializable wouldn't compile at all. :)

Upvotes: 3

ngesh
ngesh

Reputation: 13501

You cannot do this since E is not defined type/ class. for acheiving multiple inheritance you can make use of interfaces. thats the legal way..

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47363

For good or for bad, there is no multiple inheritance in Java. Generics in Java are far more different than in C++. They just give you compile type-safety. At runtime the generics information is erased.

Upvotes: 7

omnomnom
omnomnom

Reputation: 9139

Java can't do it- it's because of type erasure. When Java class is compiled, generic type (E) is changed to some concrete class / interface - compiler must be able do determine what the type is. Also, Java does not support multiple inheritance - class can extend only one class (but it can implement multiple interfaces).

Upvotes: 0

Related Questions