• Post Reply Bookmark Topic Watch Topic
  • New Topic

doubt on which methods are eligible to be called  RSS feed

 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read books and come across two different points.
At some places it says that the methods which can be called
are dependent on the type of the reference variable
while at some places it says that the methods which can be called
depends on the actual type of the object?

So please gentlemen , explain what is the real picture about the
above?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both of those aspects come into play.

At compile time, which exact signature to invoke is determined by the reference type that we're dereferencing to call the method. So, for instance, if we have

the only signatures that will be considered are those defined in the Foo class, and non-private methods in its ancestors. It doesn't matter if SubclassOfFoor has some other signature that's a better match for (arg1, arg2). The signature chosen is the best match that's available in Foo, because reference varaible f is of type Foo.

At runtime, the JVM decides which class's implementation of that exact signature to invoke by the class of the object. So if SubclassOfFoo overrides the bar(arg1, arg2) signature, then that version will be invoked. If not, the JVM will keep lookup up the tree (toward ancestor classes) until it finds the "deepest" (furthest down the tree away from Object) implementation of bar(arg1, arg2).

Compile time: signature, based on reference type.
Runtime: which class's implementation, based on object and its class hierarchy.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!