在下面的示例中,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;
}发布于 2013-06-27 10:49:46
在超类中标记受保护的属性,子类应该可以访问它们:
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;
}
}https://stackoverflow.com/questions/17329237
复制相似问题