1

次の例では、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>();
    }
}

サブクラスでは、すべてのノードに 2 つの子しかありません。以下のように書いています。

スーパークラスを最大限に活用しながら、構造を正しく保つには、メンバー フィールドとコンストラクターをどのように記述すればよいですか?

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

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

コンストラクタ BinaryNode() では、super() が呼び出されます。子への影響は?

さらに、このサンプルでは 2 つの子のみのように、サブクラスの一部のフィールドに特定の規則がある場合、再利用を最大化するためにスーパークラスとサブクラスでコンストラクターを記述する方法は?

スーパークラスに次のメソッド isLeaf() があり、サブクラスに記述しない場合。サブクラスのインスタンスで使用しようとすると、正しく機能しますか?

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

1 に答える 1

0

スーパークラスで保護された属性をマークすると、サブクラスはそれらにアクセスできるようになります。

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;
    }
}
于 2013-06-27T02:49:46.420 に答える