Why use getters and setters
In the previous article JavaBean Standard we explained the JavaBean Specification. In the current post we shall discuss JavaBeans and why use getters and setters. This is one of the favorite topic of Interviewers for 1-3 yrs experience candidates.
So the real pressing question is Why should we need getters & setters? which basically do nothing, lets consider the below Employee class which has private field name and public getters & setters for name also it has a public field department without any getters & setters for the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.heapcode.java; import java.io.Serializable; public class Employee implements Serializable { private String name; public String department; public String getName() { return name; } public void setName(String name) { this.name = name; } } |
The below code lines does the similar operation of setting value to particular field.
1 2 3 4 |
Employee employee = new Employee(); employee.setName("Manjunath"); employee.department = "Computer Science"; |
So, what is the difference between the 2nd and 3rd statement?
From task perspective they perform similar thing i.e. updating a variable with some value.
However there are significant differences which are.
- Making a field public we are providing direct access to the field, through which anyone can set a undesirable or null value without any restrictions, whereas when we use a setter, the setter method is the single point of contact & indirect access for updating the field, we can restrict what values are acceptable for field via some validations such as a null check before setting the value. By doing so everyone intending to update the field has to abide by the validation rule.
12345public void setName(String name) {if(name != null){ //perform a null check validationthis.name = name;}} - getters & setters act as one and only entry & exit point for the field. There can also be a logic added to getter wherein we decide to return the clone of the object rather than returning the actual reference.
123public Employee getEmployee(){return new Employee(this); //clone a new Employee and return the same.} - Usually most of the times getters & setters method do not have any validation checks inside them, we do that to provision any validation to be added in future.
- Many people argue to say that since we don’t have anything inside the getters & setters most of the time, why should we ever be writing them instead making the field public. But it is always better to have a few lines of code extra to support future validation rather than requiring to change each and every instance of access to public field.