16

チェーン メソッド ("this" を返すメソッド) のコレクションを定義する親クラスがあります。親クラスの代わりに子クラスのインスタンスが返されるように、独自の chainer メソッドを含むが、親メソッドも「オーバーライド」する複数の子クラスを定義したいと考えています。

各子クラスで同じメソッドを繰り返す必要はありません。そのため、すべての子クラスが共有するメソッドを含む親クラスがあります。ありがとう。

class Chain {
  public Chain foo(String s){
    ...
    return this;
  }
}

class ChainChild extends Chain {
  //I don't want to add a "foo" method to each child class
  /*
  public ChildChain foo(String s){
    ...
    return this;
  }
  */

  public ChainChild bar(boolean b){
    ...
    return this;
  }
}

ChainChild child = new ChainChild();
child.foo().bar(); //compile error: foo() returns a "Chain" object which does not define the bar() method. 
4

4 に答える 4

14

返される親クラスのメソッドは、this引き続き子クラスのオブジェクトへの参照を返します。親クラスのオブジェクトとしてのみ扱うことができますが (キャストしない限り)、実際には元の型になります。

次のようなジェネリックの使用を検討できます。

// This seems a bit too contrived for my liking. Perhaps someone else will have a better idea.
public class Parent<T extends Parent<T>> {
    T foo () {
        return (T) this;
    }
}

public class Child extends Parent<Child> {
    public void bar () {
        Child c = foo();
    }
}
于 2013-02-24T17:17:08.253 に答える
12

このサンプルは、ニーズに基づいてジェネリックを使用して作成しました。

class Parent {
    public <T extends Parent> T foo() {
        return (T)this;
    }
}

class Child extends Parent {

}

class AnotherChild extends Parent {

}

public class Test {
    public static void main(String[] args) {

        Parent p = new Child();
        System.out.println(p);
        Child c = p.foo();
        System.out.println(c);
        //throws ClassCastException here since Child is not AnotherChild
        AnotherChild ac = p.foo();
        System.out.println(ac);
    }
}
于 2013-02-24T17:20:49.607 に答える
0

あなたはそれをキャストすることができます。

ChainChild child = new ChainChild();
((ChainChild) child.foo()).bar();

あなたは試すことができます:

public ? extends Chain foo() {
    return this;
}

しかし、コンパイルされたとしても、それが役立つかどうかはわかりません。

于 2013-02-24T17:18:58.137 に答える