Java - 使用继承原始参数的参数重写方法



我有一个二叉搜索树的类:

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()中调用时,将根据对象的类调用正确的方法。

如何覆盖AVLTreeBSTree类中insert的方法以将AVLNodes 作为参数?

您必须提供实现作为类型参数(如果节点是内部类,则必须使用 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)

最新更新