+ 1

how Encapsulation protect the variables?

in encapsulation,anyone can change the value through the setter method. then how it is protect the variable? I don't understand this concept

3rd Nov 2022, 6:58 AM
mon
2 Answers
+ 4
- Encapsulation really makes sense only if you provide a setter which does some actual validation, before assigning a value. - Also, sometimes you don't even want to write a setter method, because the field can only be changed internally by your class in some complicated way that is not visible to the outside. - And sometimes you don't even want to expose the internal (private) field at all, to any other program that would use your class, in this case you wouldn't even write a getter. But in fact, all of this is just an illusion, because anything can be changed with runtime reflection. https://code.sololearn.com/ca9A17a1A4A1/?ref=app
3rd Nov 2022, 8:27 AM
Tibor Santa
Tibor Santa - avatar
+ 3
Separating getters and setters allows you to avoid modifying a value accidentally when you only need to get it. We don't have to have a setter for each attribute, it is sometimes better to have only getters if the values will never be modified after the initialization of the object. The setters also make it possible to add a particular behavior when modifying the attribute, by checking the data for example before persisting it. https://code.sololearn.com/c4UA1GmR5g7d/?ref=app
3rd Nov 2022, 7:27 AM
Roland
Roland - avatar