Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding Rules for static methods

 
midhuna peru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys ! I was trying out the following code in 3 ways.
CASE 1: eat() method in both the base class and sub class are static.


The output is


CASE 2:
Only Animal's eat() method is static, the error is


CASE 3
Only Horse's eat() method is static, the error is


What is happenning in CASE 1,2,3 ? Is eat() method overriding in CASE 1?


 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think the code from Case 1 can even be compiled, so I'm wondering how did you manage to get the output?

The errors you get in Cases 2, 3 are saying that you are trying to override method, but it's signature differs from the one in your superclass.

Note that there is a difference between method overriding and method hiding, which occurs in the context of class methods. You can read more about it here.
 
midhuna peru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops sorry...I edited the proper code. Now it works.
 
midhuna peru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks for the notes. So CASE 2 and 3 are compilation errors. But in CASE 1, this Hiding concept is completly new to me. I did not get it. I modified my main method as the following,


Output is


Now what is happening here?
 
midhuna peru
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys! I got my answers from here in detail.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic