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.
7 Antworten
+ 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
+ 2
~ swim ~ Thanks
+ 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.
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.
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?