我有一个二叉搜索树的类:
class BSTree<T> {
...
protected void insert(BSNode<T> parent, int side, BSNode<T> child){
... // Binary tree insertion logic
}
public void add(T data){
...
parent, side, child = search(data) // this line is pseudo code
insert(parent, side, child) // instance insertion logic
}
...
}
我的树的节点是BSNode
类的实例。
我正在实现BSTree
的扩展类 -AVLTree
类,它使用BSNode
的扩展 -AVLNode extends BSNode<Integer>
这是AVLTree
类:
class AVLTree extends BSTree<Integer>{
...
/* overrides BSTree insert() with slightly different parameters,
which inherit from the parameters of the BSTree insert() method */
protected void insert(AVLNode parent, int side, AVLNode child){
... // AVL tree insertion logic
}
...
}
我的问题是:
我希望AVLTree
中的insert()
方法覆盖BSTree
中的insert()
方法,以便从add()
中调用时,将根据对象的类调用正确的方法。
如何覆盖AVLTree
中BSTree
类中insert
的方法以将AVLNode
s 作为参数?
您必须提供实现作为类型参数(如果节点是内部类,则必须使用 AVLTree.AVLNode)。
class AVLTree extends BSTree<Integer, AVLNode> {
protected void insert(AVLNode parent, int side, AVLNode child) {
...
}
...
}
和
class BSTree<T, T_NODE extends BSNode<T>> {
protected void insert(T_NODE parent, int side, T_NODE child) {
...
}
...
}
不能用具有不同签名的另一个方法重写方法。因此,您不能像protected void insert(AVLNode<T> parent, int side, BSNode<T> child)
那样用 smth 覆盖protected void insert(BSNode<T> parent, int side, BSNode<T> child)
。