Programming in Java on Your Computer
- Classes and Objects in BlueJ
- Trying out Code in BlueJ
- The Code for Creating and Using Objects
- Source Code and Methods
- Accessors and Mutators
- Constructor Code
- Class Code
- Simple Debugging
- Interactive Picture
- Refactoring Code with Inheritance
Accessors and Mutators
Premium Content - Free Preview
You saw how to edit a method that returned the ID of a student. In Object-Oriented programming, you usually want to make an Object's variables
private which will prevent external code from directly accessing them. Instead, other code should use public methods of your Object for getting and modifying variable values. These methods are commonly called Accessors and Mutators.
Accessor methods simply return the value of one of the Object's variables. For example,
getStudentID() returned the Student's ID, so it's an accessor. To get the ID of
student1 in other code, you would type
Question: Why couldn't I just make the student's ID (
SID) public, which would let me type
student1.SID to get the ID?
Answer: That would work but it would violate the principle of Encapsulation, and would be much less flexible. For example, let's say you want to always return additional information with the ID. With an accessor, you were able to modify the method easily so any code that accessed the ID will receive the extra information. (If you directly accessed the variables, you would need to edit your code everywhere the variable is accessed.)
You could also run additional checks in the accessor, such as checking that there is a Student ID in the first place.
Mutators are methods that change the value of an Object's variables. They can do this by directly changing the value of a variable. For example, in a Car class, you could have a method to set the speed: