• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why do static method hiding follow Overriding rules?

 
Sudhanshu Gupta
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
As we know static methods are never Overridden. Rather they are just redefined.
However I noticed something I could not understand.



If the eat method in Fruit class is just a redefined method and not an Override,
how come compiler complains with this error:

D:\Java Programs>javac Food.java
Food.java:7: eat() in Fruit cannot override eat() in Food; attempting to assign
weaker access privileges; was public
private static void eat(){
^
1 error


Does that mean the Rules of Overriding apply here?

I also tried other violations of the rules and each result in an error related to Overriding.

One more thing,
when i removed static modifier from one of the methods, It also results in an error that too related to Overriding.


D:\Java Programs>javac Food.java
Food.java:7: eat() in Fruit cannot override eat() in Food; overridden method is static
private static void eat(){
^
1 error

please help.

 
Vivek Singh
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well that is Inheritance? As you are trying to inherit the method from the Parent class so you cannot reduce the visibilty of the method.

Where as Overriding is Polymorphism. Which applies to the instance Objects at Runtime.

I think that clears your doubt.
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sudhanshu Gupta wrote:Does that mean the Rules of Overriding apply here?


No it means the compiler produces a confusing message.

A static method of a superclass can be inherited and hidden, but never overridden.
 
Sudhanshu Gupta
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both for such a prompt response.
Now my confusion is clear.
Damn java compiler for generating such confusing messages.
Why dont they correct it?

anyways thanks again.
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sudhanshu Gupta wrote:
Why dont they correct it?


I don't know. Another example is "Null Pointer Exception". Java doesn't have pointers. It has references. Still this message is never corrected.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic