java子类问题
我有一个使用 BinaryTree
类构建的 BinarySearchTree
类。现在我想通过子类化 BinarySearchTree
类来构建一个 RedBlackTree
类。问题是 BinaryTree
类没有颜色字段。因此,我创建了一个 ColorBinaryTree
类,它是 BinaryTree
类的子类。这是我有点困惑的地方。在我的 BinaryTree 类中,我有以下方法
protected BinaryTree<E> parent(){
return parent;
}
,其中父级显然是另一个 BinaryTree 。在我的 RedBlackTree 类中,我还需要能够访问 ColorBinaryTree 对象的父对象。但是,我不能只使用从 BinaryTree
类继承的方法,因为它返回一个 BinaryTree
对象,这意味着我无法访问颜色。使用以下代码,我收到错误
ColorBinaryTree<E> parent = newNode.parent();
,其中 newNode
是 ColorBinaryTree
对象。所以在我看来,唯一的方法就是像这样覆盖我的 ColorBinaryTree 子类中的上述方法。
@Override
protected ColorBinaryTree<E> parent(){
return parent;
}
我是否缺少某种方法来获取此值,或者我是否只需要重写返回 BinaryTree 对象的所有方法?如果是这样,那似乎有点浪费,因为方法的主体完全相同。
I have a BinarySearchTree
class which is built using a BinaryTree
class. Now I want to build a RedBlackTree
class by subclassing the BinarySearchTree
class. The problem is that the BinaryTree
class doesn't have a field for color. So, I created a ColorBinaryTree
class that's a subclass of the BinaryTree
class. Here's where I get a little confused. In my BinaryTree class I have the following method
protected BinaryTree<E> parent(){
return parent;
}
where parent is obviously another BinaryTree
. In my RedBlackTree
class, I will need to be able to access parents of ColorBinaryTree
objects as well. However, I can't just use the method inherited from the BinaryTree
class because that returns a BinaryTree
object which means I can't access the color. With the following code I get an error
ColorBinaryTree<E> parent = newNode.parent();
where newNode
is a ColorBinaryTree
object. So it seems to me the only way to do it is to overwrite the above method in my ColorBinaryTree
sublcass like so.
@Override
protected ColorBinaryTree<E> parent(){
return parent;
}
Am I missing some way to get aorund this or do I just have to go and override all of the methods that return BinaryTree objects? If so it seems kind of a waste since the body of the methods are exactly the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您应该执行协变覆盖。这并不是“浪费”,因为它限制了
ColorBinaryTree
所有子类的parent
返回类型。Yes, you should do the covariant overrides. This is not "a waste", since it constrains the return type of
parent
for all subclasses ofColorBinaryTree
.您不转换超类父函数的结果是否有原因?
像这样:
也有点痛苦,但可能就是您正在寻找的。
处理它的最佳方法可能是使用返回 ColorBinaryTree 的方法覆盖返回 BinaryTree 的基类中的所有函数。然后在子类的实现中调用父类的方法并在返回之前执行强制转换。这样你的代码中就不会有一百万次的强制转换。它可能看起来像这样:
Is there a reason you're not casting the result of the superclass's parent function?
Like this:
Also kind of a pain, but probably what you're looking for.
The best way to deal with it, is to probably override all of the functions from your base class returning BinaryTree with a method that returns ColorBinaryTree. Then in the implementation of the child class call the parent's method and perform the cast there before returning. That way you don't have a million casts spread out in your code. It might look like this: