| Author |
Overriding methds
|
tural ferhadov
Greenhorn
Joined: Oct 20, 2012
Posts: 7
|
|
Why overriding method cannot have more restrictive access modifier.?
|
 |
Jeanne Boyarsky
internet detective
Marshal
Joined: May 26, 2003
Posts: 26193
|
|
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
Greenhorn
Joined: Oct 13, 2012
Posts: 28
|
|
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.
|
 |
 |
|
|
subject: Overriding methds
|
|
|