Accessor Methods

Emily Wilson
6 min read
Listen to this study note
Study Guide Overview
This study guide covers accessor methods (getter methods and toString()), focusing on how to write them in Java. It explains the purpose of getter methods and the toString() method, including examples within the Student
and Assignment
classes. The guide also discusses return types, return by value, and control flow related to method calls.
#Introduction to Accessor Methods
For the next couple of topics, we will focus on writing methods. The first type that we will consider are accessor methods. Accessor methods are methods that allow other clients (objects, classes, and users) to access the data of an object. Since we want other clients to access this, accessor methods are made public. There are two types of accessor methods:
- Getter Methods
- toString() Getter methods are used when we want to get a specific piece of data, such as the value of a certain instance variable. This is done by simply using a return statement in the method and setting the return type of the method to the type of the variable being returned.
On the other hand, the toString() method returns the information about an object as a string. This is usually done through string concatenation. As we will see when writing our toString() methods later in the section, we do not need to call the getter methods for specific instance variables. Even though the variables are private, they are in the class, so we can access these variables directly. If we try to print an object in another method, that object's toString() method is automatically called.
#Writing Accessor Methods for Our Two Classes
Now, w...

How are we doing?
Give us your feedback and let us know how we can improve