Can anyone please explain how actually Getter and Setter works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can anyone please explain how actually Getter and Setter works?

16th Nov 2016, 3:23 AM
Dharani Kumar
Dharani Kumar - avatar
3 Answers
+ 6
Getter and setter methods are used to retrieve and manipulate private variables in a different class. A "getter" method does as it name suggest, retrieves a the attribute of the same name. A setter method allows you to set the value of the attribute.
16th Nov 2016, 4:42 AM
Abdelaziz Abubaker
Abdelaziz Abubaker - avatar
+ 5
since private members of class are inaccessible, you declare two public functions called as getter and setter. for example there is a variable called as int a in private section. you define two functions in public as follows, //getter int get_a() { return this.a; } //setter void set_a(int a) { this.a=a; } So that now using these functions you can access that private member
16th Nov 2016, 4:51 AM
P Sandesh Baliga
P Sandesh Baliga - avatar
+ 2
example (not runned) String h ="a"; System.out.println(h.get()); this prints a System.out.println(h.set ("hi")); will set "a" to "hi" and print it (probably)
18th Nov 2016, 4:39 PM
Ayush chadha
Ayush chadha - avatar