You are on page 1of 3

 

Accessors (Getters) and Mutators (Setters)


 A common model for designing data access is the use
of accessor and mutator methods.
 A mutator — also known as a setter — changes some
property of an object.
o By convention, mutators are usually
named setPropertyName.
 An accessor — also known as a getter — returns some
property of an object.
o By convention, accessors are usually
named getPropertyName.
o One exception is that accessors that return a boolean value
are commonly named isPropertyName.
 Accessors and mutators often are declared public and used
to access the property outside the object.
o Using accessors and mutators from code within the object
also can be beneficial for side-effects such as validation,
notification, etc.
o You can omit implementing a mutator — or mark it private 
— to implement immutable (unchangeable) object properties.
We can update our Employee class to use access modifiers,
accessors, and mutators:
import java.util.*;
class Employee
{
   // Member variable of this class

private String name;


private int ssn;
public void setSSN(int ssn)
{
this.ssn = ssn;
}
public void setName(String name) {
if (name != null && name.length() > 0)
{
this.name = name;
}
}
public String getName() {
return this.name;
}

public int getSSN() {


return this.ssn;
}
}
Now, to set the name on an employee in 
Emp.main() (i.e., from the outside), you must call:
E1.setName("Tom");

class Emp {
public static void main (String[] args)
{
// Creating an object of class 1 in
main() method
Employee E1 = new Employee();

// Setting the name by calling setter


method
E1.setName("Tom");
E1.setSSN(123);

// Getting the name by calling geter


method
System.out.println(E1.getName());
System.out.println(E1.getSSN());
}
}

You might also like