+ 2

Getters and setters

Why are getters and setters used cant we simply declare like String color="Red"

25th Feb 2018, 8:52 AM
divyam sureka
divyam sureka - avatar
2 Answers
+ 4
Getters and Setters are used to better encapsulate and hide away your variables so that they cannot be directly accessed from outside the class. This helps to prevent unwanted changes to the value a variable holds by making the field private. This will also allow the programmer to further control the appropriate values the field is given and how the value is received. For instance, say you had a field variable of the type int named 'age'. You most likely wouldn't want the user to give a negative value to the variable. Using a setter would allow you to perform a check of the value that was passed in and take the appropriate action based upon that value. Such as, using an if statement to change the value to 0 or 1 when a negative value is passed in to avoid a runtime error further on in your code, or maybe in some case actually throwing your own custom error or logging it etc. You may also just want the value to be a read-only type in which you only have a getter without a setter and the value is set via the constructor or by some other means within the class.
25th Feb 2018, 9:10 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
It's for encapsulation, basic component of OOP
25th Feb 2018, 8:58 AM
Zayniddinova Vasilya Bakievna
Zayniddinova Vasilya Bakievna - avatar