【发布时间】:2011-06-29 18:15:13
【问题描述】:
我有一个 BinarySearchTree 类,它是使用 BinaryTree 类构建的。现在我想通过继承BinarySearchTree 类来构建RedBlackTree 类。问题是BinaryTree 类没有颜色字段。所以,我创建了一个ColorBinaryTree 类,它是BinaryTree 类的子类。这是我有点困惑的地方。在我的 BinaryTree 类中,我有以下方法
protected BinaryTree<E> parent(){
return parent;
}
其中 parent 显然是另一个 BinaryTree。在我的RedBlackTree 类中,我还需要能够访问ColorBinaryTree 对象的父对象。但是,我不能只使用从BinaryTree 类继承的方法,因为它返回一个BinaryTree 对象,这意味着我无法访问颜色。使用以下代码我得到一个错误
ColorBinaryTree<E> parent = newNode.parent();
其中newNode 是ColorBinaryTree 对象。所以在我看来,唯一的方法就是像这样在我的ColorBinaryTree sublcass 中覆盖上述方法。
@Override
protected ColorBinaryTree<E> parent(){
return parent;
}
我是否缺少某种方法来解决这个问题,还是我只需要重写所有返回 BinaryTree 对象的方法?如果是这样,这似乎有点浪费,因为方法的主体完全相同。
【问题讨论】:
标签: java inheritance tree subclass