+ 2
Getters & setters
When exactly I'm supposed to use getters and setters ?
6 Answers
+ 4
For example:
Class Example{
int x;
}
x is public. You can change x directly.
Example ex = new Example();
ex.x = 4;
Class Example{
private int x;
//setter --> setX
//getter --> getX
}
x is private. Now it is not possible to change x directly. You have to use setX (or getX to get the value of x).
Encapsulation is one part of OOP. You hide your variables and with setters and getters you get more control.
* Who can change the variables?
* Which values are accepted?
* Who have access?
https://www.sololearn.com/learn/Java/2162/?ref=app
+ 3
If for example in a class that extends a super class, the super class has a PRIVATE variable x = 2 and has a PROTECTED getX() method; The subclass can use the getX() method to set x.
+ 2
getters get the value and setters set the value.
+ 2
Getters return the value, setters don't return anything, but they change the variable.
Example:
private int x;
setX(z) {x = z };
getX(){return x}
+ 1
thank you đ