Midori Ryuu
Midori Ryuu

Reputation: 35

Dynamic cast in Java

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);

Upvotes: 0

Views: 1721

Answers (1)

Keith Randall
Keith Randall

Reputation: 23265

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.

Upvotes: 2

Related Questions