Getters and Setters in Java

Hello guys! In this tutorial, we have figure out the getters and setters method and their features in Java. We will learn accessor and mutator in the Java programming language.

Getters and Setters in Java Explained

Getters and setters are used to secure your data, especially when creating classes.
For each instance variable, a Getter method returns its value when a setter method sets or updates its value. Getters are known as accessors and Setters are known as mutators, respectively.

Note: By the Java Convention,

Getters method,

  • Start with the keyword ‘get’ with the name of the variable with the first letter of the variable as capital
  • Return the value of the attribute

Setters method,

  • Start with the keyword ‘set’ with the name of the variable with the first letter of the variable as capital
  • Take an argument and assign it a member variable

Why do developers use Setter and Getter methods?

The use of setter and getter methods allow developers to validate and control the value initialization and access. Let us understand this with an example,



public void setName(String name) {
    if(name =="" || name.length()<5){
        throw new IllegalArgumentException();
    }else{
        this.name = name;
    }

}

Lets create a Human class:

app/Human.clss
public class Human {

    // Members Variables    public String name;
    public String address;
    public int age;
    public String hearColor;

    // define getters and setters method respectively    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name =="" || name.length()<5){
            throw new IllegalArgumentException();
        }else{
            this.name = name;
        }

    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getHearColor() {
        return hearColor;
    }

    public void setHearColor(String hearColor) {
        this.hearColor = hearColor;
    }
}

In the above example, you can see that the setName() method doesn’t accept any name whose length of the name is less than 5. and you can use any condition to the setters method as your wish, it’s the power of setters method. 
Finally, I am going to tell you about getter methods. If we use the getter method then we can easily set the instance variable private. No one can access the instance variable outside of the classes. It’s the power of getter methods. Only after creating an object can call the getters method to get the value. 
It’s the advantages of Polymorphism. I will talk to the latter about Polymorphism. I hope now you can understand the setters and getter methods. If you have any doubt please comment below.