+ 2

Getters & setters

When exactly I'm supposed to use getters and setters ?

14th Mar 2019, 12:54 AM
Sâmøčhkã B-ch
Sâmøčhkã B-ch - avatar
6 ответов
+ 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
14th Mar 2019, 1:17 AM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
14th Mar 2019, 12:59 AM
Ole113
Ole113 - avatar
+ 2
getters get the value and setters set the value.
14th Mar 2019, 1:05 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 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}
15th Mar 2019, 1:53 AM
Anthony
Anthony - avatar
+ 1
thank you 😊
14th Mar 2019, 1:18 AM
Sâmøčhkã B-ch
Sâmøčhkã B-ch - avatar