Dynamic cast in Java

若如初见. 提交于 2019-12-25 03:25:14

问题


I'm not sure if this is what it's called, but here is the problem:

I have a superclass with three subclasses. Let's say Superclass, Subclass1, Subclass2,Subclass3

I have another class with the following overloaded method:

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
}

Is there a way for me to call the overloaded method from the superclass while dynamically casting the method parameter to the object type at runtime?

anotherClass.exampleMethod(this);

回答1:


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

Is that what you mean?

Probably better to do

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

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

You can then call callExampleMethod in the superclass, and it will delegate properly.



来源:https://stackoverflow.com/questions/11924617/dynamic-cast-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!