What's the point of protected fields in Java since it breaks the data encapsulation principle?

351 views Asked by At

Here are the sentences cited from "Core Java":

Suppose your class is used by other programmers and you designed it with protected fields. Unknown to you, other programmers may inherit classes from your class and start accessing your protected fields. In this case, you can no longer change the implementation of your class without upsetting those programmers. That is against the spirit of OOP, which encourages data encapsulation.

As a result, I would like to know what the point of protected fields is in Java?

2

There are 2 answers

1
leeyuiwah On BEST ANSWER

It is discouraged if the super class and sub class are not maintained by the same developer (or the same organization). However, it is a useful technique if the super class and sub class are closely coupled code. For example, components of the same library.

As an analogy, in business world every deal should be protected by some legal contracts, and one would say it is "discouraged" to make a deal without the protection of some legal contract. That would be true if the parties are different business entities. However, obviously the same principle cannot be applied when the parties are not business entities but members of the same family.

OOP is about organization of code. And in different situations different organization principles will be needed.

0
Jose Martinez On

I see it being more useful in abstract classes. For example I recently wrote an abstract class for a video game where there was a rotation field (an angle). The abstract class did not care too much about how the angle was calculated, the concrete class will be responsible for setting it as it requires. The abstract class uses it, the concrete class sets it.

There are other ways of accomplishing this. Another variation would be to have the concrete class implement a method called getAngle, which the abstract class would call when it requires the value of rotation, but I did not go this route for performance purposes.