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.
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
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.
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.
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.