4️⃣

12.4 Accessors and Mutators

Accessors and Mutators

Accessors and Mutators, more commonly called getters and setters, are special methods that allow a programmer to access and change the value of private fields.
 
They are needed because if a field is private, it can’t be accessed via dot notation since only the class the field was defined in has access to the field. Therefore, you need to use a method to indirectly get or update a field.
 
Getters return the same type as the field itself. They simply return the current value of the field. Setters return void and take 1 parameter, which is the new value of the field. The only thing setters do is assign the current field to the new value. For example, the Person class would have the following getters and setters:
/** Returns the person's name */ public String getName() { return name; } /** Sets the person's name to a new specified name */ public void setName(String name) { this.name = name; } /** Returns the person's age */ public int getAge() { return age; } /** Sets the person's age to a new specified age */ public void setAge(int age) { this.age = age; } /** Returns the person's address */ public String getAddress() { return address; } /** Sets the person's address to a new specified address */ public void setAddress(String address) { this.address = address; } /** Returns true if the person is hungry */ public boolean isHungry() { return hungry; } /** Sets hungry to a specified value */ public void setHungry(boolean hungry) { this.hungry = hungry; }
View this code on GitHub
Notice how if you are writing a getter for a boolean, such as the field hungry, you don’t say getHungry(). Rather, you would name the method isHungry().
Note: Not all fields need to have getters and setters. It just depends on how you want to design your program. For example, if a field is public, you don’t need getters and setters because a programmer can simply access the field using dot notation. In other cases, we don’t want other programmers to be able to change a certain field once it’s been initialized. For example, if I had a class called Student with a field called studentIDNumber, I probably wouldn’t want to have a setter for that field because once a student gets an ID number, it can’t be changed.

Practice

Book

Create a class called Book with 5 private fields: title (String), author (String), genre (String), numberOfPages (int), and rating (a double from 0 to 5). Create a default constructor and a 5-argument constructor. Create getters and setters for all of the fields. Bonus points if you write Javadoc comments for each of the methods!
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.