We use getters and setters:
- for reusability
- to perform validation in later stages of programming
Getter and setter methods are public interfaces to access private class members.
Encapsulation mantra
The encapsulation mantra is to make fields private and methods public.
Getter Methods:We can get access to private variables.
Setter Methods:We can modify private fields.
Even though the getter and setter methods do not add new functionality, we can change our mind come back later to make that method
- better;
- safer; and
- faster.
Anywhere a value can be used, a method that returns that value can be added. Instead of:
int x = 1000 - 500
use
int x = 1000 - class_name.getValue();
In layman's terms
Suppose we need to store the details of this Person
. This Person
has the fields name
, age
and sex
. Doing this involves creating methods for name
, age
and sex
. Now if we need create another person, it becomes necessary to create the methods for name
, age
, sex
all over again.
Instead of doing this, we can create a bean class(Person)
with getter and setter methods. So tomorrow we can just create objects of this Bean class(Person class)
whenever we need to add a new person (see the figure). Thus we are reusing the fields and methods of bean class, which is much better.