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.
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 Serializablewouldn’t compile at all. 🙂