• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding methds

 
tural ferhadov
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why overriding method cannot have more restrictive access modifier.?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34965
377
Eclipse IDE Java VI Editor
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Yin Stadfield
Ranch Hand
Posts: 58
Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic