Why do the data members of POJO classes are private and the getter/setter function are public? Can someone please give solution for this.
-
1https://en.wikipedia.org/wiki/Encapsulation_(computer_programming) – Jens Jun 02 '17 at 12:05
5 Answers
Common approach: access to variables by using getters/setters:
- better maintainability
- accessibility to private properties only for the defining class (isolation)
- used for a different data representation (you might have private data to store the birthdate, but create a getter named
getAge()
).

- 1,875
- 18
- 28
It doesn't have to be that way, it's just a pattern and it exists for a reason.
All members of a class should be private by default, so that noone can mess up things from outside or read/write values which are not important by the outside. Additionally some internal stuff can change within your class, and the outside world should not care about it.
To allow access from the 'outside world', be it reading or writing anything should be handled via getters/setters/issers to allow a governed manipulation.
Think of it like a mini API of your class - an interface to your class anyone outside can understand and rely on.

- 3,859
- 2
- 21
- 60
If you want to add any validation or modify any other thing before/after setting value of an object, you can use that validation in setter method. Same applies for getter.

- 926
- 8
- 14
It the basic object-oriented principle i.e only object can communicate through message which is called encapsulation.So indirectly you are not exposing your state to outside.For an example class with one attribute age is there and age can not be negative so in setter you can put a check so your object state will not in bad condition.If you access directly the variable then there is no scope for validation.

- 2,576
- 2
- 10
- 16
The basic principle of the oriented object programming is to encapsulate the members of a class and give access to them only via getters and setters

- 2,918
- 21
- 39