Doubts in Getters and Setters | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Doubts in Getters and Setters

I understand that Getters and Setters are used for protecting data while creating classes and it is used to set values and return values for protected attributes. But, my question is that 1. Even if don't make the attribute Private, my getter and setter methods still work. So, why use getter and setter? 2. Is there any other use of using getter and setter?

19th Jan 2019, 7:21 AM
A Grey Ninja
A Grey Ninja - avatar
2 Answers
+ 6
Encapsulation is one of the fundamentals of OOP. It refers to the bundling of data with the methods that operate on that data. Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Publicly accessible methods are generally provided in the class (so-called gettersand setters) to access the values, and other client classes call these methods to retrieve and modify the values within the object. //Wikipedia, encapsulation
19th Jan 2019, 8:34 AM
Michal
Michal - avatar