This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Proctected methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Proctected methods" Watch "Proctected methods" New topic
Author

Proctected methods

sai sirnu
Greenhorn

Joined: Oct 29, 2007
Posts: 2
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

Joined: Oct 13, 2005
Posts: 37953
    
  22
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

Joined: Oct 20, 2007
Posts: 513
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.


SCJP 5.0
sai sirnu
Greenhorn

Joined: Oct 29, 2007
Posts: 2
Thank you Kelvin Lim and Campbell Ritchie, I got clear picture now
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Proctected methods
 
Similar Threads
protected modifier
Abstract Class
finalize() method
A SCJP cram test question
Protected Vs Default