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?
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.
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.
Joined: Oct 29, 2007
Thank you Kelvin Lim and Campbell Ritchie, I got clear picture now