1

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.

Skeen
  • 4,614
  • 5
  • 41
  • 67

4 Answers4

7

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.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
3

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. :)

Thomas
  • 87,414
  • 12
  • 119
  • 157
0

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).

omnomnom
  • 8,911
  • 4
  • 41
  • 50
0

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..

ngesh
  • 13,398
  • 4
  • 44
  • 60
  • But then I'll have to copy the same code all over the place, and that's bad pratice? – Skeen Aug 26 '11 at 08:48
  • @Skeen, implement all those methods in a single class and extend it in classes where you need those methods. or you can also use objects to call methods already defined. – ngesh Aug 26 '11 at 08:50
  • Thing is, I'll be needed this class in several classes, that already extend, so I this is why I wanted to do this. – Skeen Aug 26 '11 at 08:54
  • The link Petar provided gave me a solution. – Skeen Aug 26 '11 at 08:56