Meaningless Drivel is fun!
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

Overriding methds

tural ferhadov

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

Joined: May 26, 2003
Posts: 33102

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Yin Stadfield
Ranch Hand

Joined: Oct 13, 2012
Posts: 58

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.
I agree. Here's the link:
subject: Overriding methds
It's not a secret anymore!