Getter and Setter in Java | Example Program

In this tutorial, we will learn about getter and setter method in Java with the help of various example programs.

A method which is used to retrieve/get the value of a variable or return the value of the private member variable is called getter method in Java.

This method is also known as accessor method in Java. For every private variable, we should create a getter method.

Depending on the access level giving to the variable, we can set the access modifier of its getter method. If we declare instance variables as private, we will have to add public getter methods for each one.

The general signature to declare a getter method in Java is as follows:

public returnType getXxx() {
 // Getter method's body.
}

In the above syntax, Xxx is the name of a variable and get is a keyword used to define a getter method in Java.

Consider the below example where we have declared a variable name of type String with a private access modifier.

private String name;

We can define a getter method for this variable by using JavaBeans naming convention as this:

public String getName() {
  return name; 
 }

Since the data type of variable name is String, the return type of getter method is also String.

Setter method in Java


A method which is used for updating or setting the value of a variable is called setter method in Java. This method is also known as mutator method in Java.

By using the setter method, we can modify or update the value of a variable. Just like with the getter method, we need to create a setter method for every variable in the class.

The general signature to declare a setter method in Java is as follows:

public void setXxx(formal_parameter) {
 // Setter method's body.
}

In the above syntax, Xxx is the name of variable and set is a keyword used to define setter method in Java. Let’s define a setter method for the variable name by using JavaBeans naming conventions.

public void setName(String name) {
  this.name = name; 
}

Naming Convention for Defining Getter and Setter method in Java


In Java, we can define getter and setter methods by using the JavaBeans naming convention. You must keep in mind the following rules. They are as:


1. If a variable (i.e. property) is of boolean type, the getter method’s prefix can be either is or get.

2. If a variable is not of boolean type, the getter method’s prefix must be get.

3. The prefix of a setter method must be set.

4. The signature of a setter method must be public, with void as return type, and a formal parameter that represents the variable type or property type.

5. The signature of a getter method must be public with no formal parameter, and a return type must match with the variable type.

6. After prefix get or set, the first letter of variable name should be in the uppercase.


Consider the below example code in which we have declared a variable of type int with the private modifier.

private int number;

then appropriate getter and setter will be like this:

public getNumber()  {
  return number;  
}
public void setNumber(int number)  { 
  this.number = number;
}

Similarly, if the variable is a type of boolean, then the getter and setter methods will be like this:

private boolean rich;
public boolean getRich() {return rich; }
public void setRich(boolean r) {rich = r; }

Let’s take simple example programs to understand getter and setter methods clearly.

Java Getter and Setter Example Program


1. Let’s take an example program where we will declare variables of type String and int with the private modifier. Then, we will access it using getter and setter methods in Java.

Program code 1:

package gettersetterProgram;
public class Person 
{
// Declare instance variables as private.	
   private String name;
   private int age;

// Create getter methods for each variable.
   public String getName() {
     return name;
   }
   public int getAge() {
     return age;
   }
// Create setter methods for each variable.    
   public void setName(String name) {
     this.name = name;
   }
   public void setAge(int age) {
     this.age = age;
   }
}
package gettersetterProgram;
public class Test {
public static void main(String[] args) 
{
// Create an object of class Person.
   Person p =  new Person();
// Call setter methods and set the values.
   p.setName("Jack");
   p.setAge(20);
   
// Call getter methods.
   String n = p.getName();
   int a = p.getAge();
// Print name and age on the console.
   System.out.println("Name: " +n);
   System.out.println("Age: " +a);
	}
}
Output:
      Name: Jack
      Age: 20

In the above code, the return type of getName is String. Therefore, we have stored returned value in a variable n of type string and displayed it on the console.

Similarly, the return type of getAge is int. Therefore, we have stored returned value in a variable a of type int and printed it on the console.


2. Let’s take another example where we will make a class named Mensuration. In this class, we will declare private variables and a couple of public getter and setter methods to make it read-write.

In this program, we will calculate the circumference, area of the circle, and area, perimeter of the rectangle using the getter and setter methods. Look at the program source code.

Program code 2:

package gettersetterProgram; 
public class Mensuration 
{ 
   private double l, b, r; // length, breadth, and radius.
// Create getter methods for each variable. 
   public double getL() { 
     return l; 
   } 
   public double getB() { 
     return b; 
   } 
   public double getR() { 
     return r; 
   } 
// Create setter methods for each variable in the class. 
   public void setL(double l) { 
    this.l = l; 
   } 
   public void setB(double b) { 
    this.b = b; 
   } 
   public void setR(double r) { 
     this.r = r; 
   } 
// Now write the logic to calculate the area and perimeter of rectangle
// and the circumference and area of the circle. 
   public double areaRec() { 
    double area = l * b; 
    return area; 
   } 
   public double perRec() { 
    double per = 2 * (l + b); 
     return per; 
   } 
   public double areaCircle() { 
    double area = 3.14 * r * r; 
     return area; 
   } 
   public double circumCircle() { 
    double circumference = 2 * 3.14 * r; 
    return circumference; 
   } 
 } 
package gettersetterProgram;
public class MyTest { 
public static void main(String[] args) 
{ 
  Mensuration mens; // Creating reference. 
    mens = new Mensuration(); // Creating object.
 
// Set the values of the variables. 
   mens.setL(20.5); 
   mens.setB(30.5); 
   mens.setR(12.5); 

// Call getter methods.  
   double areaRec = mens.areaRec(); 
   double perRec = mens.perRec(); 
   double areaCircle = mens.areaCircle(); 
   double circumCircle = mens.circumCircle(); 

   System.out.println("Area of rectangle: " +areaRec); 
   System.out.println("Perimeter of rectangle: " +perRec); 
   System.out.println("Area of circle: " +areaCircle); 
   System.out.println("Circumference of circle: " +circumCircle); 
 } 
}
Output: 
       Area of rectangle: 625.25 
       Perimeter of rectangle: 102.0 
       Area of circle: 490.625 
       Circumference of circle: 78.

Key points of getter and setter method


  • If you define only the getter method in the program, you can make it read-only.
  • If you define only the setter method in the program, you can make it write-only.
  • If you define both getter and setter methods in the program, you can make it both read-write.

3. Let’s create a Java program in which we will define only the getter method to read the value of the variables and make it read-only. We will declare a constructor to initialize the values of the variables. Look at the following source code step by step.

Program code 3:

package gettersetterProgram;
public class Employee 
{ 
  private String name; 
  private int id; 
  private String nCompany; 
 Employee(String name, int id, String nCompany)
 { 
   this.id = id; 
   this.name = name; 
   this.nCompany = nCompany; 
 } 
 public String getName() { 
   return name; 
 } 
public int getId() { 
   return id; 
 } 
public String getNCompany() { 
   return nCompany;
 } 
} 
package gettersetterProgram;
public class ReadOnlyTest { 
public static void main(String[] args)
{ 
  Employee em = new Employee("Deep", 23435, "TCS");

// These methods will read the value of the variables only. 
// Since the return type of these methods is String, int, and String. 
// We will store the returned values using variables name, id, and nCompany of type string, int, and string.  
   String name = em.getName(); 
   int id = em.getId(); 
   String nCompany = em.getNCompany(); 
  System.out.println("Employee's name: " +name); 
  System.out.println("Employee's id: " +id);
  System.out.println("Company's name: " +nCompany);
 } 
}
Output:
      Employee's name: Deep 
      Employee's id: 23435 
      Company's name: TCS

4. Let’s take an example program where we will define only the setter method to set the values of the variable and make it write only. Here, we will calculate the sum of three numbers and display it on the console.

Program code 4:

package gettersetterProgram; 
public class Addition
{ 
  private int x, y, z; 
  public void setX(int a) { 
    x = a; 
  } 
  public void setY(int b) { 
    y = b; 
  } 
  public void setZ(int c) { 
    z = c; 
  } 
  void sum() { 
    int s = x + y + z; 
    System.out.println("Sum: " +s); 
  }
 } 
package gettersetterProgram;
public class CalculateSum { 
public static void main(String[] args) 
{ 
 Addition a = new Addition(); 
   a.setX(10); 
   a.setY(20); 
   a.setZ(30); 
   a.sum(); 
 } 
}
Output:
       Sum: 60

In this example, we have not defined getter methods for each variable. We have only set the values of variables using setter methods, but we cannot access them outside the class without using getter methods.

Therefore, we have declared a method named sum() in the class Addition and accessed them inside the method.

Thus, the setter method is used to update or set the value of a variable, whereas the getter method is used to read the value of a variable.


Hope that this tutorial has covered all the important points related to getter and setter in Java with the help of various example programs. I hope you will have understood the basic points of getter and setter methods and practiced all example programs.
Thanks for reading!!!

Next ⇒ Encapsulation in Java⇐ PrevNext ⇒