In Object Oriented Programming languages, access specifier plays an important role in conveying, who should use what to avoid unexpected class behavior. Read another post to know about what are access specifiers, why they are needed in OOPS
Now let's understand protected access specifier by going through topics:
- Literal meaning of protected access specifier
- Significance of protected access specifier
- An example of protected access specifier
- More on private access specifier
Literal meaning of protected access specifier
When you mark a class member, property or method as protected it can only be accessed from inside the class in which it is defined and from the classes which derives from them.
Significance of protected access specifier
When a class developer has said a member as protected, he/she means that it not meant for somebody outside the class except the class derives from it. He has created the protected access member by knowing that only the class in which it is defined and the classes derive from it can access the protected members. Because the class in which it is defined and the derived classes will have right context to use or to provide the implementation for the protected access specifier.
So when writing a class, if you want to expose members, properties and methods to only the derived classes, consider marking those as protected.
Access specifier will tell the intention of the class developer on how the class should be used. So as a class developer and consumer of the class, it your responsibility to use them properly while designing your class hierarchy.
An example of protected access specifier
More on private access specifier
- If you are creating a class hierarchy, mark all base class members which you think should only be accessed by derived classes.
- Most of the times all protected methods will be marked as virtual also. So that derived classes can override to provide custom implementation.
- If your class is not going to be used a base class then don't mark any members as protected and consider marking them with private specifier.