Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When i need to use a protected access modifier [duplicate]

Tags:

java

my question is concerning about the "protected" access modifier.

I know its functionality, but I don't know when I need to use it. Conceptually methods in a class could be divided as: constructors setters/getters methods used from clients (i.e other classes) internal methods (used from other methods in the class)

like image 948
ThiepLV Avatar asked Jul 11 '13 13:07

ThiepLV


2 Answers

You use protected when

  • Your class is designed for inheritance - You expect the users of your library to inherit from the class that you are designing. Very often the class will be abstract.
  • The class provides special functionality to its derived classes that must not be visible to other classes - You know that derived classes must have access to information that would otherwise be private, or
  • The derived classes must provide functionality to the base class - See Template Method Pattern for information about this use of protected methods.

Note that protected methods are similar to public methods in the sense that once you put them in, they need to stay in for as long as you support your library. Unlike private methods that you can freely remove, protected methods remain a part of the interface of your class.

like image 93
Sergey Kalinichenko Avatar answered Nov 18 '22 07:11

Sergey Kalinichenko


Use it when you need to do some internal stuff that is not exposed in public API but still needs to be overriden by subclasses.

like image 27
Arnaud Denoyelle Avatar answered Nov 18 '22 08:11

Arnaud Denoyelle