+ 1

setter and getter

Is there any one please would like to explain me "getter" and "setter" (a snippet would be delicate) in the real world (i mean there applicability while addressing a problem), honestly i don't feel like they are necessary. Thanks in advance.

1st Mar 2020, 11:22 AM
Robel Engida
Robel Engida - avatar
2 Answers
+ 4
When you write a POJO (plain old Java object) that is a class that has some member variables and methods. You as a developer decide which details of your class you expose to the outside world (for other parts of your program or for other applications to use.) These represent the public interface of your class and it is the concept of encapsulation in OOP. It is typical practice in Java to set all instance variables as private, so they cannot be manipulated from outside. You provide public getter methods for variables that you want to expose as visible. You add setter methods only in case you want to give access to change the value. And you may build some custom validation or constraint into these setters, so in case the value is not appropriate due to business logic, it is not allowed to be set. Example: class BankAccount has a private variable balance. You want to ensure it doesn't go below zero, so you throw an exception in the setter if someone tries to assign negative value.
1st Mar 2020, 11:36 AM
Tibor Santa
Tibor Santa - avatar
+ 3
nice Tibor, thank you, see you around.
1st Mar 2020, 11:43 AM
Robel Engida
Robel Engida - avatar