Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Weaker Access Privilege

 
Satyajit Bhadange
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

when we override why cant we grant weaker access to overridden methods...i need ans in object oriented way....if weaker access to granted in subclass what are all possible problems that could come up..ans with example would be more elaborative


 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liskov substitution principle
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In what sense do you mean "weaker"? I mean, you can change a protected superclass method to public. Overriding a private superclass method obviously doesn't make sense.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assumed Satyajit meant more restrictive - e.g. changing public into protected.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To me, that'd be "stronger"--that's why I had to ask :)
 
Satyajit Bhadange
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya i meant changing public to protected..why it cant be done...
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The link provided gives a pretty detailed explanation.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15208
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Because there is an is a relationship between the superclass and the subclass (the Liskov substitution principle that Rob mentioned). If this were allowed, there would be a backdoor through which you could call methods that should not be accessible.

You can assign an instance of a subclass to a variable that has the type of the superclass:

The call in line 17 would be possible, because method() is public in class Super. But it should not be allowed, because obj is really referring to an instance of Sub, and in that class, the method is protected! So, there is a backdoor through which you could now suddenly call a method in class Sub that should not be accessible from the outside.

To prevent this, it's not allowed to give an overriding method more restricted access than the method it is overriding.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic