Cathal Cathal - 6 months ago 28
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) {

Any ideas appreciated



You almost wrote it yourself:

public void someMethod(A a) {
    if (a instanceof B) {

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