+ 1
Can anyone please explain how actually Getter and Setter works?
3 Respostas
+ 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.
+ 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
+ 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)