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 ;)
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With