[英]How to extend a class with a member of its own type?
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: 假设我们需要使用一个称为“ BaseNode”的类来实现不同类型的树,从该类派生其他类型的Node,并且它假设有一个实例变量,该实例变量称为其自身类型的
parent
,通常看起来像这样:
class BaseNode{
//...some fields
BaseNode parent;
//...other methods
}
Now if I am going to derive Node for AVL tree with more members: 现在,如果我要为具有更多成员的AVL树派生Node:
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. 原
parent
( left
和right
)节点成员仍将型BaseNode
我实现AVL树防止。 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
. 解决方案1-
(AVLNode) parent
访问parent
,都将其(AVLNode) parent
为(AVLNode) parent
。 You could write an accessor in AVLNode
to make it more convenient. 您可以在
AVLNode
编写访问AVLNode
以使其更加方便。
class AVLNode extends BaseNode {
public AVLNode getParent() {
return (AVLNode) parent;
}
}
Solution 2 - Make BaseNode
a generic class that takes the subclass as a parameter. 解决方案2-使
BaseNode
成为将子类作为参数的通用类。 Now parent
can be the exact type needed. 现在,
parent
可以是所需的确切类型。
class BaseNode<T extends BaseNode<T>> {
T parent;
}
class AVLNode extends BaseNode<AVLNode> {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.