Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Proctected methods

 
sai sirnu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys

A protected memeber is accessible in all classes in the package containing its class, and by all subclasses of its class in any package where this class is visible.
Non subclasses in other packages cannot access protected members from other packages.

Then in what scenarios we will go for protected methods, please explain me with short example, why we need this restriction?

many thanks
 
Campbell Ritchie
Sheriff
Pie
Posts: 50246
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

When you want to keep inherited members private. You can restrict them to members of the present class and its subclasses by declaring them in a superclass in a different package. I think you can override protected methods with public access (in which case they cease to be restricted), but you can't override them with private access.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another very common scenario is when your superclass uses a template method that calls other methods (e.g. task1(), task2()) to perform the actual work. The superclass provides stub implementations of these task1() etc methods, but you want sub-classes to be able to override these task1() etc methods so that they can implement more specific functionality. At the same time, however, you don't want other classes to be able to invoke those methods directly, since these are algorithm details that shouldn't be exposed.

Protected visibility is the only option that fits the bill here. Private and default visibility won't allow sub-classes to override the methods, while public visibility will expose the methods to the whole universe.
 
sai sirnu
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Kelvin Lim and Campbell Ritchie, I got clear picture now
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic