It is always recommended to use getter/setter for accessing private variables. Why would it not be a better idea to declare them as public and access them. Anyway we are accessing it using getter and setter?
Encapsulation.
Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
See also:
@mre answer is excellent and your question is fundamental. To summarize : you put the fields of an object private to gain control over the way it will be used by other objects. Your object uses setter to:
it will use getter to
welcome in the wonderfull world of OO programming and the magics of structured programming.
Stéphane
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With