简体   繁体   English

Java继承最大化重用

[英]Java Inheritance Maximize reuse

In following example, TreeNode is the superclass and BinaryNode is subclass. 在下面的示例中,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>();
    }
}

In subclass, every node has only two children. 在子类中,每个节点只有两个孩子。 I write as following. 我写如下。

How should I write the member fields and constructor to best use the superclass, yet keep the structure right? 我应该如何编写成员字段和构造函数以最好地使用超类,同时又保持结构正确?

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

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

in constructor BinaryNode(), super() is called, what's the impact on children? 在构造函数BinaryNode()中,将调用super(),这对子代有什么影响?

What's more, if the subclass has specific rules on some fields, like only two children in this sample, how to write the constructors in superclass and subclass to maximize reuse? 此外,如果子类在某些字段上具有特定的规则(例如本示例中只有两个子代),那么如何在超类和子类中编写构造函数以最大程度地重用?

if I have the following method isLeaf() in superclass and don't write it in subclass. 如果我在超类中具有以下方法isLeaf()并且不要在子类中编写它。 When I try to use it with a subclass instance, would it function correctly? 当我尝试将其与子类实例一起使用时,它是否可以正常运行?

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

You mark the attributes protected in the superclass and the subclass should have access to them: 您在超类中标记了受保护的属性,子类应该可以访问它们:

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