This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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 ?
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 sscce.org