Accessors (getters) and mutators (setters) provide a common model for accessing and modifying object properties. Accessors return a property value, following the convention getPropertyName. Mutators change a property value, following the convention setPropertyName. Accessors and mutators are usually public to allow external access and modification, and can perform validation or notification. Immutable properties are implemented by omitting mutators or making them private.
Accessors (getters) and mutators (setters) provide a common model for accessing and modifying object properties. Accessors return a property value, following the convention getPropertyName. Mutators change a property value, following the convention setPropertyName. Accessors and mutators are usually public to allow external access and modification, and can perform validation or notification. Immutable properties are implemented by omitting mutators or making them private.
Accessors (getters) and mutators (setters) provide a common model for accessing and modifying object properties. Accessors return a property value, following the convention getPropertyName. Mutators change a property value, following the convention setPropertyName. Accessors and mutators are usually public to allow external access and modification, and can perform validation or notification. Immutable properties are implemented by omitting mutators or making them private.
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();