开发者

java subclass question

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 wh开发者_C百科ich 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.


Yes, you should do the covariant overrides. This is not "a waste", since it constrains the return type of parent for all subclasses of ColorBinaryTree.


Is there a reason you're not casting the result of the superclass's parent function?

Like this:

ColorBinaryTree<E> parent = (ColorBinaryTree<E>)newNode.parent();

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:

@Override
protected ColorBinaryTree<E> parent() {
    return (ColorBinaryTree<E>)super.parent();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜