Why we need
Getters & Setters
in JAVA ?
@vikasrajputin
1. Introduction
➔ In Java classes, we normally
create the getter and setter
methods to read and update
class level fields respectively.
➔ Let's find out why do we
following this practice.
@vikasrajputin swipe left
2. Example
➔ Consider a class Account, having fields like
accountName and accountBalance - to
show the name and balance of the account.
➔ As a common practice, both the variables are
private and define the public getter and
setter method to read and write their values.
@vikasrajputin swipe left
➔ Using the previous example, let's
see different use-cases where
having getter and setter
methods can be game changing.
@vikasrajputin swipe left
3. Validation
➔ The public getter and setter method act as
a single door to access the private fields.
➔ Before updating the value we can run any
validation in the setter method and
accordingly allow field modification.
@vikasrajputin swipe left
4. Security
➔ Similar to Validation, we can also put any
security-related code to secure our data
inside the getter and setter.
➔ For eg. Check if a user has access to the field
based on our complex security logic and then
allow the user to either read or update the
value.
@vikasrajputin swipe left
5. ReadOnly & WriteOnly
➔ To allow only write permission, we can keep
setter methods.
➔ Similarly, to allow only read permission to
fields, we can remove the setter method and
only keep the getter method as shown below:
@vikasrajputin swipe left
6. Immutable Class
➔ To create an immutable class, we can remove
the setter and put-getter methods.
➔ In getter methods, we can return a new copy
instead of returning the original object to
protect it from getting modified.
@vikasrajputin swipe left
❤ Thanks for reading !
For more content on
Java & Backend Development,
follow me on below handles
Vikas Rajput
@vikasrajputin