Java继承最大化重用

Java继承最大化重用,java,inheritance,constructor,code-reuse,extends,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 A

在下面的示例中,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 TreeNode {
        protected int data;
        protected TreeNode parent;
        protected List<TreeNode> children;

    ...

    public boolean isLeaf() {
          if(this.children == null)
             return true;
          else
             return false;
    }
}
公共类树节点{
受保护的int数据;
受保护的树节点亲本;
受保护儿童名单;
...
公共布尔isLeaf(){
if(this.children==null)
返回true;
其他的
返回false;
}
}

看看这一点,这样做的目的是创建您自己的数据结构吗?如果是这样的话,
子类
应该是您拥有的类的列表或实例,即
private BinaryNode leftNode
私有二进制节点rightNode将有2个“子”实例,一个在超类中,一个在子类中。。。在子类中,您无法看到超类的“children”字段,因为它是私有的…回答isLeaf()问题:不,它将不起作用。。。试试看。。。超类中的children字段与子类中的字段不同。在你的小班里,你看不到super的孩子们。。。你需要把它保护起来,然后把小班里的孩子赶走。。。。那么你的子类将拥有“正确的”子类:)我最关心的是,我必须重写构造函数才能获得两个子功能,还是只需要重写子部分?你能给我举个例子吗?
公共类BinaryNode扩展TreeNode{…}
-你的子类仍然是这个,但是当你将父类属性标记为受保护时,子类将获得对它们的访问权。
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;
    }
}