Access Modifiers – Why Have Private Fields When Protected Is Enough?

access-modifiersencapsulationobject-oriented

Is the visibility private of class fields/properties/attributes useful? In OOP, sooner or later, you are going to make a subclass of a class and in that case, it is good to understand and be able to modify the implementation completely.

One of the first things I do when I subclass a class is to change a bunch of private methods to protected. However, hiding details from the outer world is important – so we need protected too and not just public.

My question is: Do you know about an important use case where private instead of protected is a good tool, or would two options "protected & public" be enough for OOP languages?

Best Answer

Because as you say, protected still leaves you with the ability to "modify the implementation completely". It doesn't genuinely protect anything inside the class.

Why do we care about "genuinely protecting" the stuff inside the class? Because otherwise it would be impossible to change implementation details without breaking client code. Put another way, people who write subclasses are also "the outer world" for the person who wrote the original base class.

In practice, protected members are essentially a class' "public API for subclasses" and need to remain stable and backwards compatible just as much as public members do. If we did not have the ability to create true private members, then nothing in an implementation would ever be safe to change, because you wouldn't be able to rule out the possibility that (non-malicious) client code has somehow managed to depend on it.

Incidentally, while "In OOP, sooner or later, you are going to make a subclass of a class" is technically true, your argument seems to be making the much stronger assumption that "sooner or later, you are going to make a subclass of every class" which is almost certainly not the case.