0

我不确定这是否是所谓的,但问题是:

我有一个包含三个子类的超类。假设超类,子类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 回答