0
if we have getters and setters for data members in our classes then what's the point in making those data members as private?
8 Réponses
+ 3
The point is that from setters and getters, you can exactly control *how* the value is accessed and *what* is done with it.
For example, you could specify that private value n has to be greater than 0 but <=100.
Then your public void setN(int newN) could test for it:
if(newN<1||newN>100) return;
On the other hand, if you allow public access, a user could write *any* int in there, and then you'd have no encapsulation.
Also, when defining your getter, you can specify (for objects) that only a *copy* or a representation of the internal value is given out, not the actual object.
+ 3
Seems like freely quoted:
'Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.'
https://www.javaworld.com/article/2073723/why-getter-and-setter-methods-are-evil.html
+ 1
Mirielle "getter/setter are not particularly object oriented"
What does that mean? What is the alternative to using getters and setters in OOP?
0
Mirielle Thanks for the link.
I am not really an OOP fan so don't know much about common sayings in the OOP world.