Accessor and Mutator Methods
accessors
Part of: Writing Classes
Reading and Changing State Safely Instance variables are usually private, so outside code cannot touch them directly. To let other code work with an object's state, a class exposes public methods . Two common kinds are accessors and mutators. Accessor Methods (Getters) An accessor (or getter ) returns the value of an instance variable without changing it. By convention its name starts with get, and its return type matches the variable: An accessor that returns a boolean often starts with is instead, like isEmpty(). Mutator Methods (Setters) A mutator (or setter ) changes the value of an instance variable. Its name usually starts with set, it takes the new value as a parameter, and it returns void: Because a mutator controls the change, it can validate input, something direct field access could never do: Now the object refuses impossible grades, keeping its state valid. Why Methods Instead of Public Fields Using methods as a gate between the outside world and the data gives you control: - You can validate values before storing them. - You can compute a returned value instead of storing it (getArea() from width and height). - You can change how data is stored later without breaking o
Challenge: Clamp the Volume