Why use getter and setter? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why use getter and setter?

Example : I have a variable named schoolname Then the getter and setter method will be getSchoolname() and setSchoolname() If one knows the name of one method suppose getSchoolname() isnt it obvious the setter method will be setSchoolname() then they can change the value of the variable either way! Then what is the use of getter and setter? Sorry for my grammar and long question.

6th Jun 2019, 4:46 PM
Heisenberg
Heisenberg - avatar
5 Answers
+ 3
So in your class you have fields you usually only use getters and setter methods if your field is declared private this means you can't access this field directly from outside the class scope. To access the field you need to use a setter() method which will give the field a value to get the value back you will use a getter() method this will return the value which was assigned to the field by the setter() method
6th Jun 2019, 5:00 PM
D_Stark
D_Stark - avatar
+ 2
~ swim ~ Thanks
6th Jun 2019, 6:11 PM
Shahil Ahmed
Shahil Ahmed - avatar
+ 1
because the variable you are setting and getting is presumably private in the class, so you cant access it by just doing "schoolname = java high". the getter function GETS the private variable that would otherwise be unobtainable. the SET function sets the variable that would otherwise be unobtainable. this is for security reasons and keeping your classes safe.
6th Jun 2019, 5:00 PM
koala 🐨
koala 🐨 - avatar
0
koala 🐨 classes safe from what? What security reasons? Can u explain more in details? I am curious! My view was that if i set my variables private then they can not be accessed from other class and no one can. But if i create getter and setter then i am the only one can change the values, or this is what we are trying to achieve?? But setter method can be figured out by from the getter method. Then what is the use of this getter and setter? I am sorry if i am making the questions long. I am bad at explaining.
6th Jun 2019, 5:11 PM
Heisenberg
Heisenberg - avatar
0
Okay , I also have a question Why use use encapsulation? It's only me writing the code and doing stuff Why secure something from myself?
6th Jun 2019, 5:40 PM
Shahil Ahmed
Shahil Ahmed - avatar