Hi, Can we have more restrictive modifier when we override a method for eg-If a method has public access modifier and make it protected when we override. if we can do then please explain me and if we cant then why?
SCJP1.5(81%), SCDJWS(94%), next mission SCEA (but need to wait or that)
Hi Divya, We can't have like that. The overriden method's doesnot contain more restrictive return type. It is one of the rules we have to follow. For more information please go to Kathy's book. All the best.
Originally posted by Divya Gehlot: Can we have more restrictive modifier when we override a method
No. What should be the result of this program? Parent promises that there is a function named doIt which everyone can call. But Child says: Forget it. Only subclasses have the right to call this method.
Another example. I don't take public<-->protected but public<-->default, as it is the same thing, but maybe easier to explain.
Imagine, that it were allowed to reduce visibility when overriding and you have two classes in two packages: Then the return of the method becomes inconsistent, depending on from what package the method is called. From package ranch, the overridden method is visible, and the call on an Horse object, e.g. aHorse.whatItEats() returns "hay", but when an object of the same type is called from any other package, the overridden method is invisible and anotherHorse.whatItEats() would return "general food" of the super class.
Because of these inconsistencies reducing visibility in overriding cannot be a good thing.