• Post Reply Bookmark Topic Watch Topic
  • New Topic

Method Hiding doubt  RSS feed

 
Anuraag Kumar
Greenhorn
Posts: 11
Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am trying to understand the method hiding concept. In below code why is the methodCall() in the ChildClass not getting called? As the Method() is inherited from the ParentClass, it should be able to access the methodCall() in the ChildClass right?




Output:
Parent Method call
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because ChildClass#methodCall is static and ParentClass#Method actually calls this.methodCall().
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paweł Baczyński wrote:It is because ChildClass#methodCall is static

Correct
and ParentClass#Method actually calls this.methodCall().

No, it calls ParentClass.methodCall(), not this.methodCall(). If it called this.methodCall() the output would be Child Method call, not Parent Method call.

The reason why it calls ParentClass.methodCall() is because you can't override static methods, you can only shadow them. Any call made to static methods uses the declared type (so in this case the enclosing class ParentClass), not the actual type as is the case for instance methods.
 
Junilu Lacar
Sheriff
Posts: 11485
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again, your perspective that a Parent class somehow "accesses" methods of a subclass is misleading and clouding your understanding of what's happening.

What's really happening is the result of what's called early binding (also known as static binding). The method in question is declared as a static method therefore it does not participate in polymorphism which is achieved via late binding (aka dynamic binding) which happens at run time. Calls to static methods are resolved at compile time. In this case, since the call to the static method occurs in the superclass and is not qualified by a reference of some type, the compiler will statically bind the call to the method in the superclass. If you add a direct call to the static methodCall() in the ChildClass.main() method, say after line 22, you'll see the output of line 16.
 
Junilu Lacar
Sheriff
Posts: 11485
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here are some changes to your code that illustrate the points made previously:

Output is:

Parent Method call
Child Method call
Child Method call
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!