Java继承最大化重用

时间:2013-06-26 19:52:53

标签: java inheritance constructor code-reuse extends

在下面的示例中,TreeNode是超类,BinaryNode是子类。

public class TreeNode {
    private int data;
    private TreeNode parent;
    private List<TreeNode> children;

    TreeNode() {
        this.data = 0;
        this.parent = null;
        this.children = new ArrayList<TreeNode>();
    }
}

在子类中,每个节点只有两个子节点。 我写的如下。

我应该如何编写成员字段和构造函数以最好地使用超类,但保持结构正确?

public class BinaryNode extends TreeNode {
//  int data;
//  BinaryNode parent;
    List<BinaryNode> children;

    BinaryNode() {
        super();
        children = new ArrayList<BinaryNode>(2);
    }
}

在构造函数BinaryNode()中,调用super(),对孩子有什么影响?

更重要的是,如果子类在某些字段上有特定的规则,比如本示例中只有两个子节点,那么如何在超类和子类中编写构造函数以最大化重用?

如果我在超类中有以下方法isLeaf()并且不在子类中写入它。 当我尝试将它与子类实例一起使用时,它会正常运行吗?

public boolean isLeaf() {
    if(this.children == null)
        return true;
    else
        return false;
}

1 个答案:

答案 0 :(得分:0)

您在超类中标记受保护的属性,子类应该有权访问它们:

public class TreeNode {
        protected int data;
        protected TreeNode parent;
        protected List<TreeNode> children;

    ...

    public boolean isLeaf() {
          if(this.children == null)
             return true;
          else
             return false;
    }
}