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, we will discuss in detail the use of getters and setters in Java.
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:
Output:
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.
Java Certification Training
This is comprehensive training course in Java programming language that will make you grow in your software coding career.
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:
Output:
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 in Java
Here are two real-world examples that help you to understand how to use getters and setters in Java:
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
File 1: Main.java
Output:
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
File 2: Main.java
Output:
Common Mistakes to Avoid with Java Getters and Setters
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:
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:
First, create a copy of the object inside the setter to prevent outside changes.
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:
You should return a new copy of the object to avoid external changes.
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:
5. Not Copying Objects in Setters
Directly assigning an object reference in setters can lead to issues if the object is modified externally.
Example:
Use a copy in setters to avoid external changes.
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:
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:
- 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.
- 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
- 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
- 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.
- 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.
- 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
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
- 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
- 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.
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 |
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.
If you want to learn more about Java, you can refer to our Java Course.
Getters and Setters in Java – FAQs
Q1. Are getters and accessors the same?
Yes, getters and accessors are the same, as they both take the value of a private field in Java.
Q2. What is the point of accessors?
An accessor method is a method that is used to return the value of an instance to the user.
Q3. What are the benefits of getters and setters in Java?
It mainly helps us to achieve encapsulation in Java, which is used to hide the internal state of an object.
Q4. What is the key difference between an accessor and mutator in Java?
An accessor is a class method that is used to read the data members, while a mutator is a class method that is used to change data members.
Q5. What are @getter and @setter in Spring Boot?
@Getter and @Setter in Spring Boot are annotations that automatically generate getter and setter methods for the class fields.