0

これがその名前かどうかはわかりませんが、ここに問題があります。

3 つのサブクラスを持つスーパークラスがあります。スーパークラス、サブクラス1、サブクラス2、サブクラス3としましょう

次のオーバーロードされたメソッドを持つ別のクラスがあります。

public void exampleMethod (Subclass1 object1){
//Method to be called if the object is of subclass 1
}

public void exampleMethod (Subclass2 object2){
//Method to be called if the object is of subclass 2
}

public void exampleMethod (Subclass3 object3){
//Method to be called if the object is of subclass 3
}

実行時にメソッド パラメータをオブジェクト型に動的にキャストしながら、オーバーロードされたメソッドをスーパークラスから呼び出す方法はありますか?

anotherClass.exampleMethod(this);
4

1 に答える 1

2
if (this instanceof Subclass1) {
    anotherClass.exampleMethod((Subclass1)this);
} else if (this instanceof Subclass2) {
    anotherClass.exampleMethod((Subclass2)this);
}
...

そうですか?

したほうがいいのかも

abstract class Superclass {
    abstract void callExampleMethod(AnotherClass anotherClass);
}

class Subclass1 extends Superclass {
    void callExampleMethod(AnotherClass anotherClass) {
        anotherClass.exampleMethod(this);
    }
}
... same for other subclasses ...

その後、スーパークラスを呼び出すcallExampleMethodと、適切に委任されます。

于 2012-08-12T18:22:26.777 に答える