简体   繁体   中英

Java Inheritance Maximize reuse

In following example, TreeNode is the superclass and BinaryNode is subclass.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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