#What's the point of getters and setters?
14 messages · Page 1 of 1 (latest)
They allow you to apply logic to the getting and setting it a property.
So you could validate that the value a property is being set to is valid.
Or when you get the value of a property you could convert it to a different type.
Can you please paraphrase?
I don't think it can be any simpler than adding logic to getting and setting...
Getting: obj.thing
Setting: obj.thing = 5
A getter lets you run code when you get a value.
A setter lets you run code when you set a value.
Getters let the user get the value of a private variable in a class.
Setters let the user modify the value of a private variable in a class.
But you can just make the variable public if you want the user to be able to access it.
It has nothing to do with whether it's private or public. It's just a way to get or set a value using custom logic.
"The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods."
My question is regarding this, why even add getters and setters to private variables?
Just make them public if you want them to be accessible.
You see how you could add additional logic to the get and set methods? It doesn't just have to be getting the value of setting the value. You can change the behavior to do whatever you need. That's the point of getters and setters.
The example you shared is very simple.
The value is in letting you modify what happens when you get/set.
But you can just make it public if you want it to be modifiable...