Getters and Setters in Java

getters-and-setters-in-java.jpg

Getters and setters in Java are used to control access to the data of a class and ensure encapsulation in object-oriented programming. They help to protect the data and make the code easy to maintain. With these methods, you can change the data without affecting the rest of the code and improving the flexibility and security of the code.

In this article about getters and setters Java, we will discuss in detail them in much detail.

Table of contents:

What are Getters and Setters in Java?

In Java OOP principles, getters and setters are the methods that are used to control access to the properties of an object. A getter, also known as an accessor, is a method that takes the value of a private variable, while a setter or mutator is a method that allows you to set the value of a private variable.

The main purpose of using getters and setters is to implement encapsulation in Java, which is a fundamental principle of OOP.

Getter Method in Java: Syntax, Example, and Use

The getter method in Java is used to retrieve the value of an instance variable. They start with the word “get” and are then followed by the name of the instance variable, with the first letter capitalized.

For example, for a variable “name”, the getter method would be “getName”.

Syntax for Getter Method:

public class Person {
private String name;
public String getName() {
return name;
}
}

Example:

Java

Output:

What are Getters in Java

Explanation: In the above Java code, the class Person has a private variable, name. The getName() method is a getter and gets the name. Then, an object of the Person having the name Intellipaat is created in the main method, and the getName() method is called to output it. 

Now that you understand getters in Java, let us move on to setters in Java.

Setter Method in Java: Syntax, Example, and Use

The setter method in Java is used to set the value of an instance variable. It starts with the word “set” and is followed by the name of the variable, with the first letter capitalized. 

For example, for a variable “age”, the setter method would be “setAge”.

Syntax for Setter Method:

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

Example:

Java

Output:

What are Setters in Java

Explanation: In the above Java code, the class Person has a private attribute, age. The setAge() method is used to set the age, and the getAge() method is called to get the age. Then, in the main method, the object of the Person is created.

Examples of Getters and Setters Java

You might completely understand the getter and setters in Java, their syntax and how they are used. Here are two examples that help you further grasp how to use getters and setters in Java code in the real world:

Example 1: Bank Account System

This example creates a digital version of a bank account. It keeps two details: the account number and the balance. These details are kept private so they can’t be changed directly. Instead of special methods, getters and setters are used to read or update them. The setter also checks if the balance is not negative before setting it. This helps keep the data safe and prevents mistakes. It’s a simple way to learn how to control and protect data using Java.

File 1: Bank.java

Java

File 1: Main.java

Java

Output:

Example 1 of getters and setter in Java: Bank Account System

Example 2: Student Management System

This example represents a student with two details: name and grade. These details are kept private to protect them from being changed directly. Special methods, getters and setters in Java are used to access or update the data safely. The setter for grade checks if the value is between 1 and 12, making sure only valid grades are allowed. This keeps the information accurate and helps avoid mistakes. It shows how to use Java to manage student data securely and neatly.

File 1: Student.java

Java

File 2: Main.java

Java

Output:

Example 2  of getters and setter in Java: Student Management System

Common Mistakes to Avoid with Java Getters and Setters

As a beginner, you tend to make some mistakes even though you completely grasp the concept of getters and setters in Java. Here, we have listed some common mistakes to help you avoid making them in the future.

1. Using Getters and Setters for the Public Variables. 

If a variable is public, it doesn’t need the getter and setter methods. It is recommended to keep variables private and access them via getters and setters to maintain proper encapsulation in Java.

Example:

Java

2. Usage of the Object’s Reference Directly in a Setter

Directly using an object reference in a setter without creating a copy can lead to unintended side effects

Example:

Java

First, create a copy of the object inside the setter to prevent outside changes.

Java

3. Returning Object References Directly in Getters

Returning the reference of an object directly in the getter will allow the change in the object.

Example:

Java

You should return a new copy of the object to avoid external changes.

Java

Get 100% Hike!

Master Most in Demand Skills Now!

4. Providing Setters for Public Fields

If the variable is public, directly access it. If you need control over them, first make them private and then use them.

Example:

Java

5. Not Copying Objects in Setters

Directly assigning an object reference in setters can lead to issues if the object is modified externally.

Example:

Java

Use a copy in setters to avoid external changes.

Java

6. Adding Getters and Setters for Every Field

Only add getters and setters for the fields that require external access or modification. Add the Getters and Setters in the fields that have to be accessed or changed from outside of the class. Because using them from outside the class will break encapsulation in Java and can make your code less secure.

Example:

Java

By avoiding these common mistakes, you can ensure encapsulation and more maintainable code.

Why use Getters and Setters in Java?

Getters and setters are used for the following reasons:

  1. Encapsulation: Getters and Setters support encapsulation in Java, which is used to hide the internal state of an object with the help of a private field in Java and then using the public getters and setters.  
  2. Immutability: If there is a private field in Java and only the getter is present without a setter, the object will become immutable, i.e., the data of the object cannot be changed. This is very helpful when you want to keep the values of the objects fixed
  3. Flexibility: Getters and setters make the code flexible. If you want to change how the value is returned, you can do it inside the getter and setters without changing the external code; you have to only change their setter and getters
  4. Controlling Access: By using getters and setters, you can control who can read or change the value of a field. For example, you can make the getter public so that anyone can read the value, and make the setter private or protected so only specific classes can change it.
  5. Correct Value Assignment: A setter can be used to check the value of a variable before saving it, as you can add the rules and conditions in the setter method, so that only the valid data is assigned to the field.
  6. Abstraction: Getters and setters help to fulfill abstraction, which is a Java OOP principle. The other classes or modules deal with the object by calling its public methods without knowing how the object is structured or how the fields are managed internally. This hides complexity and makes the system easier.
Free Online Java Certification Course
This free self-paced course will help you build your fundamentals in Java
quiz-icon

Why Use Getters and Setters Instead of Public Fields?

Here are the points that help you understand why we use getters and setters instead of public fields in Java:

  • Control Access: Getters and setters let you control how a private field in Java is read or updated.
  • Validation: Setters allow you to add rules (e.g., no negative numbers) before saving values.
  • Encapsulation: They help follow the Java OOP principle of hiding internal details from other classes.
  • Safe Code Updates: You can change how data works inside without breaking other code that uses it.
  • Debugging Made Easier: You can add print statements inside getters/setters to trace bugs.
  • Better Maintenance: Your code stays clean, organized, and easier to manage over time.

Benefits of Getters and Setters in Java

There are many benefits of using getters and setters in Java and that is why devopers are advised to use them often. Here is a list of reasons why:

  • Encapsulation: Getters and setters in Java hide the internal details of a class and only expose what is needed.
  • Data Protection: Setters can include validation to prevent invalid or harmful data.
  • Flexibility: You can change the internal logic later without affecting other parts of the code.
  • Readability: Code becomes easier to understand and manage with clear methods for access.
  • Debugging Support: You can add logging or print statements inside getters or setters to trace issues.
  • Standard Practice: It follows Java’s best practices and improves consistency in code structure.

Best Practices for Writing Getter and Setter Methods

FInally, before we dive into the alterantive methods to getters and setters in Java, let us discuss the best practices that you must remember while using there methods in your code.

  • Use clear and meaningful names: Start getters with get and setters with set, followed by the field name (e.g., getName(), setName()).
  • Keep fields private: Always make class variables private so only getters and setters can access them.
  • Add validation in setters if needed: For example, check if the value is not negative or empty before setting it.
  • Don’t include extra logic in getters: Keep getters simple, as they should just return the value.
  • Use setters only when needed: If a value shouldn’t be changed after creation, skip the setter to make it read-only.
  • Keep methods short and readable: Avoid long or complex logic inside these methods to keep your code clean.

Alternatives to Traditional Getters and Setters in Java

For a long time, writing Getters and setters in Java for private fields has been one of the best practices advised to developers. However, it might quickly become repetitive and result in boilerplate code. They make the code clutter, and the main logic often gets lost in between the lines. To solve this problem, Java developers have come up with many solutions, some of which we will discuss below one by one.

1. Lombok Annotations

Lombok is a library that automatically generates the getters and setters in Java at compile time. You don’t have to write many lines of code for them; you can just call the lombok in-built methods. You can do this by incorporating this code.

Code:

Java

Why Use Lombok?

  • Cleaner Code: This method is quite popular nowadays, because Lombok lets you automatically generate getters and setters in Java without having to write a manual line of code.
  • Reduced Boilerplate: Boilerplate code refers to sections of code that are repeated with little to no variation across multiple parts of a program or even across different projects. ombok helps you avoid that.
  • Compile-time generations: Since these getter and setter methods are generated at compile time beforehand, it reduces the runtime overhead by far.

2. Java Records (Java 14+)

This alternative you can use with Java version 14 and above. Java records are immutable data carriers that automatically generate a constructor, equals(), hashCode(), and toString() methods. Therefore, instead of setters, they use constructor-based initialization. This is done in teh following manner:

Java

Why Use Java Records?

  • Immutable by Default: Java records encourage functional and thread-safe design, as they make all the fields final. Final applies restrictions on any method, variable, or class, making them safe from modifications.
  • No setters needed: Since values cannot change after creation, it eliminates the risk of accidental state changes. Hence, no setters are needed.
  • Concise Syntax: The syntax for Java records is concise, which is ideal for DTOs (Data Transfer Objects) and simple methods, where you only need data storage without additional behaviours.

3. IDE Code Generation

Most modern IDEs (like IntelliJ IDEA, Eclipse, and NetBeans) provide built-in tools to generate getters and setters automatically. They assist you in writing getters and setters in Java automatically and save you time.

Example:

In the IntelliJ IDE, you can easily insert them using Alt + InsertGetter and Setter syntax.

Why use IDE Generations?

  • Consistent code style: It follows your project’s formatting rules and therefore reduces the chances of any errors. It generates perfect getters and setters in Java.
  • Time-saving: As discussed above, it supports quick generation during development and saves you time.

4. Kotlin Data Classes (Interoperable with Java)

If your project uses a mix of Java and Kotlin, Kotlin data classes offer an elegant way to create model classes with automatic getters, setters (for mutable fields), and other utility methods like equals() and hashCode().

Java

Why Use Kotlin Data Classes?

  • Extra Utility Methods: Unlike traditional getters and setters, tools like Lombok or Java records also auto-generate toString(), equals(), and copy() methods, saving time, reducing errors, and improving debugging, comparisons, and immutability.
  • Highly Concise: It reduces a full many lines of Java code to just one line of Kotlin code, saving time and space, making our code more organized.
  • Interoperable: And yes, Kotlin is fully compatible with Java-based projects, so you can use it with any kind of project.

5. Project Valhalla (Future Feature)

While still in development, Project Valhalla aims to improve data handling in Java with inline types that could reduce the need for traditional accessor methods. Let us discuss how it will be better than getter and setter in Java in the future.

Why Use Valhalla in the Future?

  • Performance-oriented design: It will offer a lower memory footprint and faster execution.
  • More expressive syntax: This will reduce the need for traditional getter and setter patterns, especially for simple value types.

Difference Between Getter and Setter in Java

Aspect Getter Setter
Purpose To retrieve the value of a private field in Java To modify or set the value of a private field in Java
Method Prefix get (e.g., getAge()) set (e.g., setAge(25))
Return Type Returns the data type of the field (e.g., int) Usually void, as it doesn’t return anything
Parameters No parameters Takes one parameter
Access Level Typically public Typically public
Functionality Only reads and returns the value Validates and updates the field value
Side Effects Should not change any data May include validation or business rules
Best Practice Should be simple and return a value only Should include checks before updating
Overloading Rarely needed Often overloaded to handle different value types
Use Case When you want to read data safely When you want to safely update data
Immutability Used alone for read-only fields Not used in immutable fields
Security Concern Low risk Needs proper checks to avoid incorrect assignments

Useful Resources

Conclusion

In Java, getters and setters play an important role in maintaining encapsulation and guaranteeing data integrity. The getters allow access to the private fields in Java of a class, while setters allow controlled changes to those attributes. By using getters and setters, users can create robust and maintainable code that follows the principles of encapsulation in Java.

Master getters and setters in Java with our hands-on course and sharpen your skills with curated interview questions. Start learning today to boost your coding confidence and ace your next Java interview.

Getters and Setters in Java – FAQs

Q1. Are getters and accessors the same in the context of getters and setters in Java?

Yes, getters (also called accessors) are the same, as they both retrieve the value of a private field in Java.

Q2. What is the point of accessors when using getters and setters in Java?

Accessors provide controlled access to private fields, ensuring encapsulation and allowing additional logic when retrieving data.

Q3. What are the benefits of getters and setters in Java?

Getters and setters in Java help maintain encapsulation, allow validation of input data, and make the code easier to maintain and modify in the future.

Q4. What is the key difference between an accessor and mutator in getters and setters in Java?

In getters and setters in Java, an accessor (getter) retrieves the value of a field, while a mutator (setter) updates or modifies it.

Q5. What are @Getter and @Setter annotations in Spring Boot for implementing getters and setters in Java?

In Spring Boot, @Getter and @Setter annotations (from Lombok) automatically generate the getter and setter methods in Java at compile time, reducing boilerplate code.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner