Mutator Methods in Java
In Java, mutator methods, also known as setter methods, are used to modify the state of an object by changing the value of its fields or attributes. These methods are commonly used in classes to ensure controlled access and modification of the class's fields.
It therefore means that corresponding to each get method, programmers also provide a public set method to change the value of a private instance variable in a class.
These methods are void, meaning that they do not return a value, but they do take a parameter, which will become the new value for the instance variable.
syntax;
class ExampleTemplate{
private typeOfVar varName;
public void setVarName(typeOfVar, newValue){
varName = newValue;
}
}
Why use accessor and mutator methods?
public class Person {
private String name;
private int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Mutator method for setting the name
public void setName(String name) {
this.name = name;
}
// Mutator method for setting the age
public void setAge(int age) {
this.age = age;
}
// Accessor method for retrieving the name
public String getName() {
return name;
}
// Accessor method for retrieving the age
public int getAge() {
return age;
}
}
Mutator methods provide an excellent opportunity to apply access control and validation to ensure data integrity within a class. Here are some examples of access control and validation techniques that can be applied using mutator methods in Java:
领英推荐
public void setAge(int age) {
if (age >= 0 && age <= 120) { // Valid range for age
this.age = age;
} else {
// Handle invalid age input (throwing an exception, setting a default value, etc.)
System.out.println("Invalid age value!");
}
}
2. Enforcing Constraints on String Length: For attributes like a username or password, you might want to limit the length of the input string.
public void setUsername(String username) {
if (username.length() >= 3 && username.length() <= 20) { // Valid username length
this.username = username;
} else {
// Handle invalid username length
System.out.println("Invalid username length!");
}
}
3. Ensuring Unique Values: In scenarios where uniqueness matters (like email addresses in a user database), you can check and enforce uniqueness.
public void setEmail(String email) {
if (isEmailUnique(email)) {
this.email = email;
} else {
// Handle duplicate email address
System.out.println("Email already exists!");
}
}
private boolean isEmailUnique(String email) {
// Check if the email is unique in the database
// Return true if unique, false otherwise
// Example implementation:
// return !database.contains(email);
}
4. Immutable Fields: You can also enforce immutability for certain fields by not providing a mutator method for those fields. Once set during object creation, their values cannot be changed.
public class ImmutableExample {
private final String immutableField;
public ImmutableExample(String value) {
this.immutableField = value;
}
public String getImmutableField() {
return immutableField;
}
}
5. Access Control with Conditions: You might have additional conditions that need to be met before setting certain attributes.
public void setRole(String role) {
if (isAdmin() && isValidRole(role)) {
this.role = role;
} else {
// Handle unauthorized role change
System.out.println("Unauthorized or invalid role!");
}
}
private boolean isAdmin() {
// Check if the user has admin privileges
// Return true if admin, false otherwise
}
private boolean isValidRole(String role) {
// Validate if the role is allowed or valid
// Return true if valid, false otherwise
}