如何使用自己类型的成员扩展类?
假设我们需要使用一个名为BaseNode的类实现不同类型的树,从中派生出其他类型的节点,它假设有一个名为 parent
的实例变量它自己的类型,通常看起来像:
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
}
现在如果我要去为更多成员派生AVL树节点:
Now if I am going to derive Node for AVL tree with more members:
class AVLNode extends BaseNode{
//...other useful stuff
}
原来的父母
(& left
& right
)节点成员仍将是 BaseNode
这阻止我实现AVL树。
任何能告诉我如何解决这个继承问题的人?
谢谢!
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!
解决方案1 - 任何时候访问 parent
,将其强制转换为(AVLNode)parent
。您可以在 AVLNode
中编写一个访问者,以使其更方便。
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;
}
}
解决方案2 - 制作 BaseNode
将子类作为参数的泛型类。现在 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> {
}