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:
Understanding Getters and Setters in Java
In object-oriented programming (OOP), 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, which is a fundamental principle of OOP.
What are Getters in Java
Getter methods are the methods in Java that are 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 to be 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.
What are Setters in Java
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 to be 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.
Java Getters and Setters: Some Common Errors
1. Using Getters and Setters for the Public Variables.
If a variable is public, it doesn’t need the getter/setter methods. It is recommended to keep variables private and access them via getters and setters to maintain proper encapsulation.
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 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, which is used to hide the internal state of an object by making the fields private and then using the public getters and setters.
- Immutability: If the field is private 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. 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
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 of a class, while setters allow controlled changes to those attributes. By using getters and setters, the users can create robust and maintainable code that follows the principles of encapsulation.
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.
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?
It mainly helps us to achieve encapsulation, which is used to hide the internal state of an object.
Q4. What is the key difference between an accessor and a mutator?
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.