articles

Home / DeveloperSection / Articles / Getter and Setter in Java

Getter and Setter in Java

Devesh Kumar Singh4163 16-Nov-2015
What are Getter and Setter in Java?
 

Getter and setter methods are used in Java to retrieve and manipulate private variables in a different class. A “getter” method does as it name suggest, retrieves the attribute of the same name. A ”setter” method allows you to set the value of the attribute.

 

Why and when we use them?

 

Getter and Setter methods aid in data encapsulation. Actually you can design programs without using them and javac won't complain. But in that case since your variables are declared public it would easier to tamper with from outside. By using getter and setter methods you make sure your variables are only set in a way you decide. 

Following is the example of a java program using getter and setter : 
public class EncapsulationDemo{
    private int ssn;
    private String empName;
    private int empAge;

    //Getter and Setter methods
    public int getEmpSSN(){
        return ssn;     }
    public String getEmpName(){
        return empName;
    }
    public int getEmpAge(){
        return empAge;
    }

    public void setEmpAge(int newValue){
        empAge = newValue;
    }
    public void setEmpName(String newValue){
        empName = newValue;
    }
    public void setEmpSSN(int newValue){
        ssn = newValue;
    }
}
public class EncapsTest{
    public static void main(String args[]){
         EncapsulationDemo obj = new EncapsulationDemo();
         obj.setEmpName("Mario");
         obj.setEmpAge(32);
         obj.setEmpSSN(112233);
         System.out.println("Employee Name: " + obj.getEmpName());
         System.out.println("Employee SSN: " + obj.getEmpSSN());
         System.out.println("Employee Age: " + obj.getEmpAge());
    }

}
Output:

Employee Name: Mario

Employee SSN: 112233

Employee Age: 32


Updated 27-Mar-2018

Leave Comment

Comments

Liked By