Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : inherits a generic type [duplicate]

Tags:

java

generics

Possible Duplicate:
Extend from Generic Supertype?

Hi everyone. I come from C++ and I loooved working with templates. I would like, in Java, to "insert" a node into the inheritance tree at a particular point. ... I think code would be more explicit :

public class MyClass<E> extends E {}

It would work fine with C++ templates but java gives me a "cannot refere to type parameter as supertype". Is there a way to do that in java ?

Thanks for your help ;)

like image 539
timelzayus Avatar asked May 02 '11 16:05

timelzayus


People also ask

Can generic types be inherited Java?

Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.

Is it possible to inherit from a generic type?

You can't inherit from a Generic type argument. C# is strictly typed language. All types and inheritance hierarchy must be known at compile time. . Net generics are way different from C++ templates.

Does Java have generic types?

Java Generics was introduced to deal with type-safe objects. It makes the code stable. Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types.

What does generic type mean in Java?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.


1 Answers

To understand the problem with the code you tried, consider what would happen if E were, say, Integer?

You can do what you want with nodes that contain generic data:

public class Node<T> {
    T data;
    // other tree bookkeeping fields
}

Then you can define subclasses:

public class ThreadedTreeNode<T> extends Node<T> {
    // even more bookkeeping fields
}
like image 186
Ted Hopp Avatar answered Oct 20 '22 15:10

Ted Hopp