Do you think IIT Guwahati certified course can help you in your career?
No
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 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
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.
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
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());
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);
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
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
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
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.