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, Returns

Mutators are named in the setBlank syntax where the Blank is the name of the field you want to modify. Mutators, like other methods in Java, take one or more parameters. Since mutators are type void as they do not return a value but rather they modify the object’s state.

// A class representing a Car with attributes like make, model, and speed.
public class Car {
    // Private fields (attributes)
    private String make;
    private String model;
    private int speed;
    // Constructor to initialize attributes
    public Car(String make, String model, int speed) {
        this.make = make;
        this.model = model;
        if (speed >= 0) {  // Ensure speed is non-negative
            this.speed = speed;
        } else {
            System.out.println("Speed cannot be negative, setting speed to 0.");
            this.speed = 0;
        }
    }
    // Mutator (Setter) for 'make' field
    public void setMake(String make) {
        this.make = make;
    }
    // Mutator (Setter) for 'model' field
    public void setModel(String model) {
        this.model = model;
    }
    // Mutator (Setter) for 'speed' field
    public void setSpeed(int speed) {
        if (speed >= 0) { // Ensuring the speed is non-negative
            this.speed = speed;
        } else {
            System.out.println("Speed cannot be negative.");
        }
    }
    // Display car details
    public void displayCarInfo() {
        System.out.println("Make: " + make);
        System.out.println("Model: " + model);
        System.out.println("Speed: " + speed + " km/h");
    }
}
// Create an instance of the Car class using the constructor and demonstrate the mutators
Car myCar = new Car("Honda", "Civic", 100);
// Displaying car info to verify the set values from constructor
myCar.displayCarInfo();
// Modifying the cars speed using the mutator
myCar.setSpeed(150); // Valid speed update
myCar.displayCarInfo();
myCar.setSpeed(-50); // Invalid value, should trigger a warning

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 fields
    private String name;
    private int age;
    private double height;
}