Mutators/Setters

Mutators are used to modify the attribute of an object. They are typically public methods to allow external code to modify the object state.

Naming & Parameters

Mutators are named in the setBlank syntax where “Blank” is the name of the field you want to modify. Mutators, like other methods in Java, take one or more parameters.

Return Type

Since mutators are type void as they do not return a value but rather they modify the object’s state.

Validation

Mutators often include validation logic to ensure that the new values are being set within acceptable bounds. An example of validation being used with mutators can be seen with the setSpeed mutator that doesn’t allow negative values.

Mutators Diagram

Lets take a look at an example!

This example discusses showcases some of the most vital use cases for mutators

// A class representing a Car with attributes like make, model, and speed.
public class Car {
    private String brand;
    private String model;
    private int speed;

    // Constructor to initialize attributes
    public Car(String brand, String model, int speed) {
        this.brand = brand;
        this.model = model;
        if (speed >= 0) {  
            this.speed = speed;
        } else {
            System.out.println("Speed cannot be negative, setting speed to 0.");
            this.speed = 0;
        }
    }
    //Mutators 
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setModel(String model) {
        this.model = model;
    }
    public void setSpeed(int speed) {
        if (speed >= 0) { //Validation so speed is not negative
            this.speed = speed;
        } else {
            System.out.println("Speed cannot be negative.");
        }
    }
    // Display car details
    public void displayCarInfo() {
        System.out.println("Brand: " + brand);
        System.out.println("Model: " + model);
        System.out.println("Speed: " + speed + " mph");
    }
}
Car myCar = new Car("Honda", "Civic", 100);
myCar.displayCarInfo();

// Modifying attributes mutators
myCar.setSpeed(150);
myCar.setBrand("Rolls Royce");
myCar.setModel("Phantom");
myCar.displayCarInfo();

//Testing Validation with invalid value (Should trigger warning)
myCar.setSpeed(-50); 
Brand: Honda
Model: Civic
Speed: 100 mph
Brand: Rolls Royce
Model: Phantom
Speed: 150 mph
Speed cannot be negative.

Popcorn Hack

1. Create a Class

Define a class Person with private fields: String name, int age, and double height. This is done for you.

2. Create Mutators

Write mutator methods setName(String name), setAge(int age) (with validation for non-negative age), and setHeight(double height) (with validation for non-negative height).

3. Write a Constructor

Create a constructor that initializes name, age, and height with provided values.

4. Test the Mutators

In the main method, create a Person object, modify its fields using the mutators, and print the details after each modification.

public class Person {
    private String name;
    private int age;
    private double height;
    
    public Person(String name, int age, double height) {
        this.name = name;
        setAge(age);
        setHeight(height);
    }
    
    
    // Set name
    public void setName(String name) {
        this.name = name; 
    }
    
    // Set age with validation
    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        } else {
            System.out.println("Age cannot be negative.");
        }
    }
    
    // Set height with validation
    public void setHeight(double height) {
        if (height >= 0) {
            this.height = height;
        } else {
            System.out.println("Height cannot be negative.");
        }
    }
    
    // Getters for displaying info
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public double getHeight() {
        return height;
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a new Person object
        Person person = new Person("Alice", 25, 5.5);
        
        // Print initial values
        System.out.println("Initial: " + person.getName() + ", Age: " + person.getAge() + ", Height: " + person.getHeight());
        
        // Modify name
        person.setName("Bob");
        System.out.println("After name change: " + person.getName());
        
        // Modify age
        person.setAge(30);
        System.out.println("After age change: " + person.getAge());
        
        // Modify height
        person.setHeight(6.0);
        System.out.println("After height change: " + person.getHeight());
        
        // Attempt to set invalid values
        person.setAge(-5);  // Invalid age
        person.setHeight(-1.5);  // Invalid height
    }
}

Main.main(null);
Initial: Alice, Age: 25, Height: 5.5
After name change: Bob
After age change: 30
After height change: 6.0
Age cannot be negative.
Height cannot be negative.