1

I understand that one should use protected when one wants to make the variable visible in all classes that extend current class, but what does that mean exactly? What are the most common use cases?

I suppose another way to frame the question would be, what are the key cases when you would want a class variable to be visible from the class' children but not from external classes.

JDelage
  • 13,036
  • 23
  • 78
  • 112
  • As an aside, protected in java also exposes the variable to all classes in the same package, which significantly lessens its protection. – Wug Sep 13 '12 at 17:56
  • @Niko - thanks for the pointer, but the answers don't really give use cases. – JDelage Sep 13 '12 at 17:59

2 Answers2

2

Most of the use cases of the 'protected' access modifier I've encountered, are instantiations of the 'Template Method' pattern.

In this pattern, a detail of an algorithm is delegated to the subclass.

In effect, protected access creates a hole in your class invariants: a subclass may abuse the member in such a way that your invariant doesn't hold anymore.

Most of the time, there are better design alternatives than protected access, dependency inversion being the first one coming to mind.

My advise? Don't publish your object's internals to anyone you don't trust. Use 'protected' with caution!

xtofl
  • 40,723
  • 12
  • 105
  • 192
1

Protected variables help effectively access the variables of base class without going through the get / set constraints.

The usefulness of protected variables are significant in development of libs which are supposed to serve in other applications. It helps you freely use the variables in the environment of lib without making them public and when you finalize the inherited class, they are barred to outside environment.

Murtuza Kabul
  • 6,438
  • 6
  • 27
  • 34