Search code examples
javaoverridingsubclasssuperclassextends

Call subclass method from a superclass method?


My app has a structure similar to this:

class Father{
a(){ ... }

b(){a();}
}

class Son extends Father{
a(){ ..... }} //override

b() is not overrided. When I create an instance of Son and I call b(), Father's a() is called, but I would like it executes the Son one (if the object is a Son). Is it possible?


Solution

  • Son's a method should be called. If it's not, then you're either not operating on an instance of Son or you haven't correctly overridden the method. This could happen if the signatures aren't exactly the same. I would double check in your implementation that the signatures are exactly the same. Also, try throwing an @Override above the Son implementation of a and see if you get a compile error. If you do, then you aren't overriding the method correctly.

    Like this

    class Son extends Father{
      @Override
      a(){ ...}
    }
    

    Also, a must be either protected or public (package private, the default, will only work if Father and Son are in the same package). i.e. Son must be able to "see" the a() method.