GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding methds Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding methds" Watch "Overriding methds" New topic
Author

Overriding methds

tural ferhadov
Greenhorn

Joined: Oct 20, 2012
Posts: 7
Why overriding method cannot have more restrictive access modifier.?
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30580
    
154

Suppose I have:

And code in another class that calls it:


All is well. The method is public. Now what happens if I have

If this did compile, eatMultiple has a problem if I call it with Apples. It can no longer call Apple's method (assuming it is in another package) since it isn't public.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Yin Stadfield
Ranch Hand

Joined: Oct 13, 2012
Posts: 43

tural ferhadov wrote:Why overriding method cannot have more restrictive access modifier.?


It can't because it will raise a compile error. It can however, declare a less restrictive access modifier. Here's the hierarchy of access modifier (1 being the most restrictive):
1 - private
2 - default
3 - protected
4 - public

If your superclass method is declared as default (no access modifier written), you can override it with the value of 2 - 4( just go down the hierarchy), but you can't go up to 1 (private) because you're making the method more restrictive.

Hope it helps. Thanks.
 
GeeCON Prague 2014
 
subject: Overriding methds