Call a method of subclass in Java

If you know that thing contains a Subclass, you can do:

((Subclass) thing).specialMethod()

The others have already mentioned how to cast objects to get an answer to your question, but asking that question in the first place points to a possible design problem. Some possible reasons:

  • The method is in the wrong place.
  • The code which calls the method is in the wrong place.
  • The subclass should not extend the other class. It's best to prefer composition over inheritance. And when inheriting, the code should follow the Liskov substitution principle.
  • The classes are non-cohesive, they have more than one responsibility, and they should be split into multiple classes.

You have to cast it to be able to invoke the method:

Base thing = new SubClass();

((SubClass) thing ).specialMethod();

If you face this situation, most likely you don't have the right interface ( the right set of methods )

Before going deep into the stage where you start validating everything to know if you can invoke a method or not like in:

 public void x ( Base thing ) {
     if( thing.instanceof Subclass ) {
         ((SubClass)thing).specialMethod();
     }
 }

Consider if you don't need to move the specialMethod up in the hierarchy so it belongs to the base.

If you definitely don't need it in the base, but you need it in the subclass at least consider use the correct type:

 SubClass thing = ... 
 // no need to cast
 thing.specialMethod();

But as always, this depends on what are you trying to do.


When dealing with inheritance/polymorphism in Java there are basically two types of casts that you see:

Upcasting:

Superclass x = new Subclass();

This is implicit and does not need a hard cast because Java knows that everything the Superclass can do, the Subclass can do as well.

Downcasting

Superclass x = new Subclass();

Subclass y = (Subclass) x;

In this case you need to do a hard cast because Java isn't quite sure if this will work or not. You have to comfort it by telling it that you know what you're doing. The reason for this is because the subclass could have some weird methods that the superclass doesn't have.

In general, if you want to instantiate a class to call something in its subclass, you should probably just instantiate the subclass to begin with -- or determine if the method should be in the superclass as well.


You have to type, or cast thing to the subclass. So:

      Subclass thing = new Subclass();

or:

     ((Subclass) thing).specialMethod();