繁体   English   中英

Java继承最大化重用

[英]Java Inheritance Maximize reuse

在下面的示例中,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;
}

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

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM