Suppose we need to implement different types of tree with a class called "BaseNode" from which other type of Nodes are derived and it suppose to have an instance variable called parent
of its own type, generally it looks like:
class BaseNode{
//...some fields
BaseNode parent;
//...other methods
}
Now if I am going to derive Node for AVL tree with more members:
class AVLNode extends BaseNode{
//...other useful stuff
}
the original parent
(&left
&right
)node members will still be type BaseNode
which prevents me to implement the AVL tree.
Any one who could tell me how we could solve this inheritance problem?
Thanks!
Solution 1 - Any time you access parent
, cast it to (AVLNode) parent
. You could write an accessor in AVLNode
to make it more convenient.
class AVLNode extends BaseNode {
public AVLNode getParent() {
return (AVLNode) parent;
}
}
Solution 2 - Make BaseNode
a generic class that takes the subclass as a parameter. Now parent
can be the exact type needed.
class BaseNode<T extends BaseNode<T>> {
T parent;
}
class AVLNode extends BaseNode<AVLNode> {
}
来源:https://stackoverflow.com/questions/50053642/how-to-extend-a-class-with-a-member-of-its-own-type