File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overriding" Watch "Overriding" New topic


pramod talekar
Ranch Hand

Joined: Apr 26, 2010
Posts: 323

Could you please tell me more on this :-

If I have a superclass Animal and a subclass Horse in a same package called Test,

If class Animal has public eat() method
and the class Horse extends Animal and has protected eat() method , // so that this eat() will be available in Test package

now If I write Animal animal = new Horse();;

The above code will result in error and suggest me to change the visibility of Horse's eat() method to public.
It says, the subclass overriding method can't have lesser visibility for that particular method

Now , if we keep the overriding rule aside for some time,

then doesn't the compiler see that the Animal class has got both eat() methods , one which is its own and other through protected access ?

The compiler can check that at compile time, there is a method with name eat() in Animal, so it should compile fine and at runtime there is another method eat() which is protected,
so its' available throughout the code, still it's failing....

Isn't the overriding rule opposite to Access laws ?


marc weber

Joined: Aug 31, 2004
Posts: 11343

pramod talekar wrote:...the Animal class has got both eat() methods , one which is its own and other through protected access ? ...

The Animal class does not have 2 eat() methods. In fact, neither does the subclass, Horse. According to JLS - 6.4.3...
A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited.

The Animal class has 1 eat() method, which is public. Suppose a reference to a Horse instance is upcast to type Animal.

Now we expect to be able to call eat() on that reference as a public method. And due to polymorphism, we expect the overridden version of eat() to be invoked for the specific subclass of Animal.

However, if you were allowed to give eat() less visibility in the subclass, then there would be a problem, because it can no longer can be invoked as a public method.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link:
subject: Overriding
It's not a secret anymore!