Table of contents
1.
Introduction
2.
What are Getter and Setter methods in Java?
3.
Why Use Getter and Setter?
3.1.
1. Encapsulation
3.2.
2. Data Validation
3.3.
3. Read/Write Control
3.4.
4. Code Maintenance
4.
Example of Getter and Setter in Java
4.1.
Java
4.2.
Explanation
5.
Need of Getter and Setter in Java
6.
Encapsulation and Data Hiding in Java
6.1.
Importance of Encapsulation in Java
6.2.
How Getters and Setters Support Encapsulation
7.
Naming Convention for Getter and Setter
7.1.
Naming Conventions for Getter Method
7.1.1.
The Syntax for Getter Method
7.2.
Naming Conventions for Setter Method
7.2.1.
The Syntax for Setter Method
8.
Bad Practices in Getter and Setter Methods
8.1.
Using Getter and Setter for Less Restricted Variables
8.2.
Java
8.3.
Using Reference of an Object Directly in a Setter
8.4.
Java
8.5.
Returning Object References from the Getter
8.6.
Java
9.
Advantages of Getter and Setter in Java
10.
Disadvantages of Getter and Setter in Java
11.
Real-World Applications
12.
Advanced Use Cases
13.
Frequently Asked Questions
13.1.
What is the difference between get and set method in Java?
13.2.
What are default getters and setters java?
13.3.
What is final getter and setter in java?
13.4.
How to use Lombok for getter and setter?
14.
Conclusion
Last Updated: Jul 1, 2025
Easy

Getter and Setter in Java

Author Aditya Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, the getter and setter methods are encapsulated and they are like the tiny buttons used to do various actions in Java. One of the four concepts of object-oriented programming is encapsulation. "Encapsulation" refers to the grouping of data and the functions that use it within an object in object-oriented programming.

getter and setter in java

Getter and setter in Java are techniques that give us a regulated way to access or modify the values of variables. In contrast to a setter method, a getter method "gets" the value of a variable and returns it.

What are Getter and Setter methods in Java?

Getters and setters are Java methods for gaining access to and changing the contents of private variables, commonly referred to as fields, in a class. The value of a private field is retrieved using a getter method. On the other hand, a private field's value can be changed using a setter method. 

Access to a class's private fields can be restricted using getters and setters. The values of the fields can be accessed and changed in a controlled manner by using getters and setters, which are provided along with making the fields private.

Why Use Getter and Setter?

1. Encapsulation

Encapsulation is a core principle of object-oriented programming. Getters and setters allow us to hide the internal data (fields) of a class and expose it only through controlled methods. This prevents external code from directly accessing or modifying fields.

private String name;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
You can also try this code with Online Java Compiler
Run Code


Using this pattern makes the class secure and ensures that its internal state is well-protected.

2. Data Validation

Setters allow us to validate data before assigning it to a variable. This helps maintain clean and safe data in objects.

public void setAge(int age) {
    if (age > 0) {
        this.age = age;
    }
}
You can also try this code with Online Java Compiler
Run Code


Without setters, fields could be updated with invalid values, leading to inconsistent object states.

3. Read/Write Control

By defining only a getter or only a setter, you can make a field read-only or write-only.

// Read-only field
public String getEmail() {
    return email;
}

// Write-only field
public void setPassword(String password) {
    this.password = password;
}
You can also try this code with Online Java Compiler
Run Code


This is useful when you want to expose only part of the data, such as displaying usernames while hiding passwords.

4. Code Maintenance

Using getters and setters improves future maintainability. If you later decide to change how a field is retrieved or modified, you only need to update the getter or setter method—without changing the entire codebase.

public String getFullName() {
    return firstName + " " + lastName;
}
You can also try this code with Online Java Compiler
Run Code


Centralizing access logic reduces bugs and makes the code easier to update or refactor.

Example of Getter and Setter in Java

Let’s see an example where we are using Getter and Setter to get the area of a Rectangle.

  • Java

Java

public class Rectangle {
   private int width;
   private int height;

   // Getter for width property
   public int getWidth() {
       return width;
   }

   // Setter for width property
   public void setWidth(int newWidth) {
       if (newWidth > 0) {
           width = newWidth;
       }
   }

   // Getter for height property
   public int getHeight() {
       return height;
   }

   // Setter for height property
   public void setHeight(int newHeight) {
       if (newHeight > 0) {
           height = newHeight;
       }
   }

   // Method to calculate area of rectangle
   public int calculateArea() {
       return width * height;
   }

   public static void main(String[] args) {
       Rectangle r1 = new Rectangle();
       r1.setWidth(5);
       r1.setHeight(10);
       int area1 = r1.calculateArea();
       System.out.println("Area of rectangle 1: " + area1);
       Rectangle r2 = new Rectangle();
       r2.setWidth(-5);
       r2.setHeight(20);
       int area2 = r2.calculateArea();
       System.out.println("Area of rectangle 2: " + area2);  
 }
}
You can also try this code with Online Java Compiler
Run Code


Output

output

Explanation

In this code, the Rectangle class 'width' and 'height' fields are accessed and changed using getter and setter, respectively. The getWidth() and getHeight() functions are used to obtain the values for the fields 'width' and 'height'. The setWidth() method sets the field 'width' and the setHeight() method is also used to set the 'height' value.

Need of Getter and Setter in Java

Getter and Setter are used in Java to access and modify values of private fields. Here are some of the reasons why getter and setter are needed.

  • Getter and Setter encapsulate the fields of a class So that the internal state of a class is hidden from the outside world.
     
  • Getter and Setter control access to field class, For example, getter can be used to provide read-only access to a field.
     
  • Setter can be used to verify the values that are set for the field.
     
  • Getter and setter have great compatibility with Java frameworks.

Encapsulation and Data Hiding in Java

Importance of Encapsulation in Java

Encapsulation is a fundamental principle of Object-Oriented Programming (OOP) in Java. It refers to the concept of bundling data (fields) and the methods that operate on that data into a single unit—usually a class. This design pattern keeps the internal workings of a class hidden from the outside world, allowing access only through well-defined interfaces (methods).

In Java, fields are typically declared as private to hide them from direct access, ensuring that they cannot be changed or read arbitrarily from outside the class. This provides a layer of security, helps prevent unintended changes, and makes it easier to manage, debug, and maintain code.

Encapsulation also allows developers to make internal changes to a class without affecting other parts of the application, resulting in modular and flexible design.

How Getters and Setters Support Encapsulation

Getter and Setter methods play a crucial role in implementing encapsulation in Java. Since variables are declared as private, they cannot be accessed directly from outside the class. Instead, getters (getX()) retrieve values, and setters (setX(value)) update them, allowing developers to control and validate access.

For example, using a setter, we can restrict negative values from being assigned:

public class Employee {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        } else {
            System.out.println("Invalid age.");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


This ensures the internal state remains valid, secure, and predictable. By using getters and setters, we not only enforce encapsulation but also allow for additional logic like validation, formatting, or logging during field access or updates.

Naming Convention for Getter and Setter

Naming Conventions are necessary to make the code more readable and maintainable.

Naming Conventions for Getter Method

  • The name of the Getter method should start with get keyword followed by the field name, capitalising only the first letter.
     
  • For Boolean Fields name of the getter method starts with is keyword.
     

The Syntax for Getter Method

public class <class_name>{
   Private <data_type> <variable_name>;
   public int get<variable_name>() {
      return <variable_name>;
   }
}


Naming Conventions for Setter Method

  • Name of Setter method should start with set keyword followed by the field name, capitalising only the first letter.
     
  • The setter method should have one parameter of the same type as the field.
     

The Syntax for Setter Method

public class <class_name>{
   private <data_type><variable_name>;
   public void set<variable_name>(<data_type> var) {
      this.<variable_name> = var;
   }
}

Bad Practices in Getter and Setter Methods

While using getter and setter in Java we should be careful with some bad practices that should be avoided.

  • Getter and Setter should not expose the internal implementation of the class.
     
  • We should avoid overusing Getter and Setter because it can make the code harder to read sometimes.
     
  • Getter and setter should not provide unrestricted access to the field.  

Using Getter and Setter for Less Restricted Variables

In Java, getter and setter methods are commonly used to access and modify an object's attributes. These methods provide controlled access to the fields and can be used to add additional logic or validation when getting or setting values.

  • Java

Java

class Student {
private String name;
private int age;

// Constructor
public Student(String name, int age) {
this.name = name;
this.age = age;
}

// Getter for name
public String getName() {
return name;
}

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

// Getter for age
public int getAge() {
return age;
}

// Setter for age
public void setAge(int age) {
if (age > 0) { // Ensure age is positive
this.age = age;
} else {
System.out.println("Age must be positive!");
}
}
}

public class Main {
public static void main(String[] args) {
// Create a Student object
Student student = new Student("Rahul", 20);

// Access and modify using getter and setter
System.out.println("Name: " + student.getName());
student.setName("Mohit"); // Using setter
System.out.println("Updated Name: " + student.getName());

student.setAge(25); // Using setter
System.out.println("Updated Age: " + student.getAge());
}
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Name: Rahul
Updated Name: Mohit
Updated Age: 25


Explanation

  • The Student class has private variables name and age.
  • Getter methods getName() and getAge() return the values of the private variables.
  • Setter methods setName() and setAge() allow you to modify the values, with setAge() ensuring the value is positive.
  • We can change the name and age of the student object using the setter methods.

Using Reference of an Object Directly in a Setter

In Java, you can pass the reference of an object to a setter method to modify the attributes of the object directly. This is useful for copying or modifying an entire object's state.

  • Java

Java

class Person {
private String name;
private int age;

// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Setter method that accepts an object reference
public void setPersonDetails(Person person) {
this.name = person.name;
this.age = person.age;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {
return age;
}
}

public class Main {
public static void main(String[] args) {
// Create two Person objects
Person person1 = new Person("Meena", 30);
Person person2 = new Person("Rani", 40);

// Modify person1's details using person2's details
person1.setPersonDetails(person2);

System.out.println("Person1 Name: " + person1.getName() + ", Age: " + person1.getAge());
}
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Person1 Name: Rani, Age: 40

Explanation

  • We have two Person objects: person1 and person2.
  • The setter method setPersonDetails() takes a Person object and updates person1's name and age to match those of person2.
  • This demonstrates using the reference of another object (person2) to modify the properties of person1.

Returning Object References from the Getter

In Java, a getter method can return an object reference, which allows external code to directly access or modify the internal state of that object.

  • Java

Java

class Book {
private String title;
private String author;

// Constructor
public Book(String title, String author) {
this.title = title;
this.author = author;
}

// Getter method to return the object reference
public Book getBook() {
return this; // Return the current object reference
}

// Getter methods for title and author
public String getTitle() {
return title;
}

public String getAuthor() {
return author;
}
}

public class Main {
public static void main(String[] args) {
// Create a Book object
Book book = new Book("1984", "George Orwell");

// Get the reference of the object using the getter
Book bookReference = book.getBook();

// Access the attributes of the returned object reference
System.out.println("Book Title: " + bookReference.getTitle());
System.out.println("Book Author: " + bookReference.getAuthor());
}
}
You can also try this code with Online Java Compiler
Run Code

 

Output

Book Title: 1984
Book Author: George Orwell

Explanation

  • The getBook() method returns a reference to the current Book object (this).
  • We use this reference to access the attributes title and author outside the class.
  • This approach allows external code to interact with the object via the getter method, returning an object reference for further operations.

Advantages of Getter and Setter in Java

We occasionally use Java methods called Getter and Setter while writing long codes in Java. These Methods benefit us in various ways.

  • They assist us in maintaining the structure of our code by hiding internal implementations of the class.
     
  • Getters and setters can limit who has access to or can modify an object's internal data. 
     
  • We can change the code behaviour with the help of getters and setters without changing all the other components of the program.

Disadvantages of Getter and Setter in Java

Using Getter and Setter in Java has several benefits for us but also some significant drawbacks.

  • The use of getter and setter can complicate our code. To view how our objects are accessed and changed, we must implement additional methods and logic, which are difficult to grasp and confusing.
     
  • Our program can occasionally run more slowly when using getters and setters. This is because these methods require some extra steps that can use more time and resources.
     
  • Using getter and setter might increase the size and complexity of our code. To handle each property, we want to access or edit. We must write more methods and logic, which might result in more complex code.
     
  •  Maintaining organised and secure code might take more work when using getter and setter methods.

Real-World Applications

JavaBeans are reusable software components that follow a standard naming convention using getter and setter methods. A typical JavaBean includes private fields, public getX() and setX() methods, and a no-argument constructor. This design allows external frameworks to access properties dynamically.

Frameworks like Spring and Hibernate rely on these standard getter and setter patterns for critical functionalities. In Spring, dependency injection often uses setters to inject configuration values or beans:

public class User {
    private String name;
    public void setName(String name) { this.name = name; }
    public String getName() { return name; }
}
You can also try this code with Online Java Compiler
Run Code


In Hibernate, ORM mapping works by calling getters/setters via reflection to read from or write to a database. Using annotations like @Column or @Autowired, frameworks manage object fields indirectly through methods, promoting encapsulation and flexibility. These patterns support clean, scalable, and maintainable code.

Advanced Use Cases

There are scenarios in Java where only a getter or setter is needed, depending on the access control required.

For example, a read-only property like a user ID might only have a getter, while a write-only field like a password may only expose a setter for security reasons.

public class Account {
    private String password;

    public void setPassword(String password) {
        if(password != null && password.length() >= 8) {
            this.password = password;
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


In such cases, setter methods can also handle input validation, like checking for null values, validating formats, or applying business rules. Another use case is calculated properties where the getter returns a derived value:

public int getAge() {
    return Period.between(birthDate, LocalDate.now()).getYears();
}
You can also try this code with Online Java Compiler
Run Code


These patterns help encapsulate logic, protect internal state, and enhance security and usability in real-world applications.

Frequently Asked Questions

What is the difference between get and set method in Java?

The get method retrieves the value of an object's attribute, while the set method modifies the value of an object's attribute in Java.

What are default getters and setters java?

When we declare a private member in a class, the default getter and setter are generated. The getter method is named get followed by the name of the private member, and the setter method is named set followed by the name of the private member

What is final getter and setter in java?

final getter is a getter method, and setter is a setter method. Both cannot be overridden by subclasses. This is done by declaring the getter or setter method as final.

How to use Lombok for getter and setter?

To use Lombok for getters and setters, we need to add the Lombok dependency to the project and then use the @Getter and @Setter annotations on private members.

Conclusion

This article discusses the topic of Getter and Setter in Java. We hope this blog has helped you enhance your knowledge of Java timestamp. If you want to learn more, then check out our articles.

Live masterclass