What is the use of getters and setters in java?

Getters and Setters are mainly used to hide the details about the fields of a class. Suppose we have a class, named Car. As we know, class in a blueprint of an object. So, the Car class is the blueprint of real object Car.

Now Car object has engines and wheels. We are using only these fields for the simplicity. Now it’s always preferred to use private access modifier. In general the class should look like as below:-

public class Car {
 // These fields are not accessible directly by other classs 
	private int wheels;
	private String engine;
	}

Now, the reason why we have selected the private access modifier, is because we want to prevent other users to use this variables and also to minimize the effort of future amendment of code. Now we want to use this Car Object and want to initialize it.

Suppose, we will use this car blueprint to define our Honda car. So for that we can use the below piece of code to initialize it. Here “Honda” is the reference of this newly created Car object.

public class Main {

	public static void main(String[] args) {
		
		//Honda Car object is initialized
		Car Honda = new Car();
		
}
}

Now, we want to define the fields value of the Car class specific to Honda Car. That means for Honda car, we have four wheels and lets assume has four-stoke engine. So to set these values we have to access the fields of that class, but those fields are not available in the Main class as in the Car class we have defined them as private only.

So here the concept of Getters and Setters comes into the picture. So the main concept is, we will define public methods which will work as an interface to set the value on this private fields and also to fetch the value from this private fields. And that interface is accessible by other classes as it is made as public.

The corresponding code snippets is:-

Now, if we want to access these fields and set values on these fields, then we have to use only these public methods only. Directly, these fields will not be accessible.

The high lighted methods are now accessible from Main class

And the output will be:-

Main Uses of Getters and Setters:-

  • To hide the fields defined in the class. These method works like encapsulation. It’s provide an cover and works like an Interface as shown above. That’s why it’s called in Java as encapsulation. So it made the code much more secure.
  • Protect codes from any unwanted changes or setting unwanted values to these private fields, which can further lead to a code break.
  • And last but not least, it removes the repetition work if any changes happens in the code. Now, if any changes happens in the private fields, then we only have to change the getters and setters methods only.