+ 1

Can Anyone Explain What is getter and setter with an example ?

It would be nice if the example covers all the things that one should know about getter and setter.

3rd Feb 2017, 7:28 AM
Abhijith R
Abhijith R - avatar
2 Answers
+ 1
Getters and setters are there for accessing private variables of other classes. For example you have the class "Dog" that has a private object variable String called "name". From the outside you can't change the name like this: Dog dog = new Dog(); Dog.name = "Fluffy"; It wouldn't compile. Therefor you create Setters and Getters in the Dog class to set and get the Dogs name, without touching the variable directly from the outside. You simply tell a Dog Object to do it itself.
3rd Feb 2017, 9:55 AM
Jannick
0
a getter gets somtehing and a setter sets an new value to the variable wich you declared private in your class. so let me give you an example: public class Test{ private int variable; public void setVariable(int variable){ this.variable = variable; <- with the this. operator you reference to the private variable } public int getVariable{ rerurn variable; } }
3rd Feb 2017, 9:06 AM
seyfullah
seyfullah - avatar