Cathal Cathal - 19 days ago 5
Java Question

calling a method an argument if it is instance of subclass

I have three java classes

class A {}

class B extends A {
public void doSomething() {}
}

class C extends B {}


I have a method which takes an argument of class A. Within that method I'd like to check if the passed parameter is an instance of class B or it's subclass. If so I'd like to cast it and call doSomething. Is this possible or advised?

something like:

public void someMethod(A a) {
if (a is instance of or subclass of B) {
(B)a.doSomething();
}
}


Any ideas appreciated

C

Answer

You almost wrote it yourself:

public void someMethod(A a) {
    if (a instanceof B) {
        ((B)a).doSomething();
    }
}

If it's a subclass of B it's also an instance of B. You just need to cast the object before trying to call the method (hence cast inside parenthesis).

Comments