Tags

, ,

Getters and setters in Java are used for modifying a class property from outside the class. Getters are used to read the properties and setters are used to write a value for the property.

These also allows to access a private property of a parent class from a sub class.
Following program illustrates the use of getters and setters:

public class vehicle1 {

private int wheels; //private variable for a class, cannot be accessed from outside of this class
String model;


public int getWheels() { // getter method
return wheels;
}

public void setWheels(int wheels) { // setter method
this.wheels = wheels;
}

}
class Car extends vehicle1 { // Inheritance


public static void main(String[] args) {

Car myCar1 = new Car(); // First Car Object
myCar1.model = "BMW";
myCar1.setWheels(6);


Car myCar2 = new Car(); // Second Car Object
myCar2.model = "Toyota";
myCar2.setWheels(5);

int x = myCar1.getWheels();
System.out.println("myCar1 has " + x + " wheels");
// System.out.println(myCar1.wheels); // will throw an error because wheels is a private variable.

int y = myCar2.getWheels();
System.out.println("myCar2 has " + y + " wheels");
}

}

Getters and setters are also called as accessors and mutators.

Getters do not have arguments. Getter method name is the property name (starting with a capital letter) prefixed by get.

Setters never return anything.  Setter method name is the property name (starting with a capital letter) prefixed by set.

Found one more interesting use of getters and setters which is for performing  a validation to decide the value to be set. Lets say, wheels should be assigned a value only when it is less than 6, else it should be 0 (not a very logical example!!!).  It can be done as below:


public void setWheels(int wheels) {
if ( wheels > 6 ) {
this.wheels = 0;
} else {
this.wheels = wheels;
}
}

Advertisements