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.

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

so, how will I achieve the wanted effect?
I see, so I'll just have to do the wrapper functions then.
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. :)

1 Comment

Stumbled across this old question somehow and have no idea why this wasn't the accepted answer.
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).

Comments

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

4 Comments

But then I'll have to copy the same code all over the place, and that's bad pratice?
@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.
Thing is, I'll be needed this class in several classes, that already extend, so I this is why I wanted to do this.
The link Petar provided gave me a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.