开发者

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 S开发者_Python百科on 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). i.e. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜