我有以下类层次结构:
public class Node<T extends Comparable>
{
private T element;
private Node<T> rightChild;
private Node<T> leftChild;
public Node(T element)
{
this.element = element;
}
public Node()
{
}
public T getElement()
{
return element;
}
public void setElement(T element)
{
this.element = element;
}
public Node<T> getRightChild()
{
return rightChild;
}
public void setRightChild(Node<T> rightChild)
{
this.rightChild = rightChild;
}
public Node<T> getLeftChild()
{
return leftChild;
}
public void setLeftChild(Node<T> leftChild)
{
this.leftChild = leftChild;
}
}
public class RedBlackNode<T extends Comparable> extends Node<T>
{
public RedBlackNode(T element)
{
super(element);
this.isRed = true;
}
private boolean isRed;
public boolean isRed()
{
return isRed;
}
public void setRed(boolean red)
{
isRed = red;
}
@Override
public RedBlackNode<T> getRightChild()
{
return (RedBlackNode<T>) super.getRightChild();
}
@Override
public RedBlackNode<T> getLeftChild()
{
return (RedBlackNode<T>) super.getLeftChild();
}
}
在子类RedBlackNode中是否可以使用方法getRightChild
,因此它将返回RedBlackNode
而不是父Node
?对我来说,一个可能的解决方案是在RedBlackNode
中覆盖此方法,但还有更优雅的方法吗?
更新 我添加了代码如何覆盖,但不确定是否有任何改进余地:)
答案 0 :(得分:0)
我认为所有树节点类型和specialize的通用接口都将实现公共接口。如果需要客户端api可以通过类型转换调用专门的方法
public interface TreeNode<V> {
public V getValue();
public TreeNode<V> getLeftChield();
public TreeNode<V> getRightChield();
public void setLeftChield(TreeNode<V> treeNode);
public void setRightChield(TreeNode<V> treeNode);
}
class Node<V> implements TreeNode<V> {
V value;
int count;
TreeNode<V> left;
TreeNode<V> right;
TreeNode<V> parent;
public Node(V value, TreeNode<V> parent) {
this.value = value;
this.parent = parent;
}
public V getValue() {
return value;
}
public TreeNode<V> getLeftChield() {
return left;
}
public TreeNode<V> getRightChield() {
return right;
}
public void setLeftChield(TreeNode<V> leftNode) {
left = leftNode;
}
public void setRightChield(TreeNode<V> rightNode) {
right = rightNode;
}
}