Search code examples
javaoopencapsulation

Can encapsulation be achieved in Java with getter and setter methods that are not public?


As I've come to understand it, encapsulation (in Java) is the mechanism of wrapping related data and methods into objects in a way, that the data is hidden from other classes and only accessible through the methods of the current class (a.k.a. data hiding), correct me if I'm wrong.

While reading some tutorials, I see that they specify that the getter and setter methods should be public.

I get why it shouldn't be private but why not protected or default? Would the use of protected or default getter and setter methods still count as encapsulation?


Solution

  • Encapsulation in Java is achieved by making a class's fields private. Weaker encapsulation is achieved by making them protected.

    Getter and setter methods do not implement encapsulation. Rather, they provide a mechanism for certain kinds of interaction with encapsulated data. If the data were not encapsulated then getter and setter methods would not be required. As such, sure, you can provide protected or default-access getters and setters, and even private ones. Or none at all. It's all a question of what features you want your class to expose to whom.

    When one makes getters and setters public it is because they provide features that are essential for use of the class, not because that level of access is a requirement for encapsulation.