简体   繁体   中英

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?

No/Yes

  • No: "When I create an instance of Son and I call b(), Father's a() is called," That is wrong!
  • Yes: "but I would like it executes the Son one (if the object is a Son). Is it possible?" -- That is the behavior of Java

If a is not a static method, then java use dynamic binding , so the son's a() method is called.

new Son().b() will invoke the method a() in Son. That is called dynamic binding.

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). ie Son must be able to "see" the a() method.

What you have should be correct. Method calls are binded lazily. This means that when you call the method a() anywhere in a Son object, it will be Son 's method that will be called.

Overridden methods are resolved at runtime whereas overloaded methods are resolved at compile time. Hence just invoking new Son().a() should be enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM