📚

 > 

💻 

 > 

⚙️

5.4 Accessor Methods

4 min readjune 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

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, we will write accessor methods for our two classes. Note that we do not write accessor methods for all our instance variables because we want some of them to stay private. This will be used with correctAnswer in the Assignment class and age in the Student class. 

Note how we use @Override when we use toString(). We will learn about that in Unit 9!

/** Represents an assignment that a student will complete
*/
public class Assignment {
  private boolean correctAnswer; // represents the answer to an assignment, either T/F

  /** Makes a new assignment with one True/False question and sets the correct answer
  */
  public Assignment(boolean answer) {
    correctAnswer = answer;
  }
  
  **/** Prints details about the assignment
  */
  @Override
  public String toString() {
    return "This is an assignment with correct answer " + answer;
  }**

}

/** Represents a high school student
*/
public class Student {
  private int gradeLevel; // a grade between 9-12
  private String name; // the students name in the form "FirstName LastName"
  private int age; // the student's age, must be positive
  private Assignment assignment; // the current assignment the student is working on

  /** Makes a new student with grade gradeLev, name fullName, and age ageNum
  */
  public Student(int gradeLev, String fullName, int ageNum) {
    gradeLevel = gradeLev;
    name = fullName;
    age = ageNum;
    assignment = null; // There is no active assignment at the moment
  }

  **/** Returns the student's grade level
  */
  public int getGradeLevel() {
    return gradeLevel;
  }
  
  /** Returns the student's name
  */
  public String getName() {
    return name;
  }
  
  /** Returns the current assignment the student is working on
  */
  public Assignment returnCurrentAssignment() {
    return assignment;
  }

  /** Prints details about the student
  */
  @Override
  public String toString() {
    return name + ", a " + gradeLevel + "th grade high school student";
  }**
}

Return Expressions

It is important to note the return types of the getter methods we write; these methods are non-void since we want them to return a value. The return type of a specific getter method is the same type as the instance variable whose value we want to get. 

  • For example, the getter method that gives us the value of the student's name should have a return type of String. That's why its method header is: public String getName().
  • In contrast, the getter method that gives us the gradeLevel for a student should have a return type of int. That's why its method header is: public int getGradeLevel(). When there is a value for the getter method to return, it will return a copy of that value. This is called "return by value." 

When the getter method has to return a reference to an object, a copy of that reference is returned, not a copy of the object. 

Once the return keyword is triggered in a method, the program immediately returns to the point after whatever called the method.

To see this control flow in action, let's look here. Assume that this is in the main method of some other class:

System.out.println("Starting the example.");

Student bob = new Student(10, "Bob Smith", 16);

System.out.println(bob);

System.out.println("End of example.");

First, the program in the main method will print out "Starting the example."

Next, the program in the main method will create an instance of the Student class by using the Student constructor. It will initialize gradeLevel to 10, name to "Bob Smith," age to 16, and assignment to null. With the creation of this object, the computer will move on to the next line of the main method. 

To print out bob, the program in the main method will use the toString() method of the Student class, which will return a String ("Bob Smith, a 10th grade high school student") that will then be printed.

Lastly, the program in the main method will print out "End of example."

<< Hide Menu

📚

 > 

💻 

 > 

⚙️

5.4 Accessor Methods

4 min readjune 18, 2024

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

Avanish Gupta

Avanish Gupta

Milo Chang

Milo Chang

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, we will write accessor methods for our two classes. Note that we do not write accessor methods for all our instance variables because we want some of them to stay private. This will be used with correctAnswer in the Assignment class and age in the Student class. 

Note how we use @Override when we use toString(). We will learn about that in Unit 9!

/** Represents an assignment that a student will complete
*/
public class Assignment {
  private boolean correctAnswer; // represents the answer to an assignment, either T/F

  /** Makes a new assignment with one True/False question and sets the correct answer
  */
  public Assignment(boolean answer) {
    correctAnswer = answer;
  }
  
  **/** Prints details about the assignment
  */
  @Override
  public String toString() {
    return "This is an assignment with correct answer " + answer;
  }**

}

/** Represents a high school student
*/
public class Student {
  private int gradeLevel; // a grade between 9-12
  private String name; // the students name in the form "FirstName LastName"
  private int age; // the student's age, must be positive
  private Assignment assignment; // the current assignment the student is working on

  /** Makes a new student with grade gradeLev, name fullName, and age ageNum
  */
  public Student(int gradeLev, String fullName, int ageNum) {
    gradeLevel = gradeLev;
    name = fullName;
    age = ageNum;
    assignment = null; // There is no active assignment at the moment
  }

  **/** Returns the student's grade level
  */
  public int getGradeLevel() {
    return gradeLevel;
  }
  
  /** Returns the student's name
  */
  public String getName() {
    return name;
  }
  
  /** Returns the current assignment the student is working on
  */
  public Assignment returnCurrentAssignment() {
    return assignment;
  }

  /** Prints details about the student
  */
  @Override
  public String toString() {
    return name + ", a " + gradeLevel + "th grade high school student";
  }**
}

Return Expressions

It is important to note the return types of the getter methods we write; these methods are non-void since we want them to return a value. The return type of a specific getter method is the same type as the instance variable whose value we want to get. 

  • For example, the getter method that gives us the value of the student's name should have a return type of String. That's why its method header is: public String getName().
  • In contrast, the getter method that gives us the gradeLevel for a student should have a return type of int. That's why its method header is: public int getGradeLevel(). When there is a value for the getter method to return, it will return a copy of that value. This is called "return by value." 

When the getter method has to return a reference to an object, a copy of that reference is returned, not a copy of the object. 

Once the return keyword is triggered in a method, the program immediately returns to the point after whatever called the method.

To see this control flow in action, let's look here. Assume that this is in the main method of some other class:

System.out.println("Starting the example.");

Student bob = new Student(10, "Bob Smith", 16);

System.out.println(bob);

System.out.println("End of example.");

First, the program in the main method will print out "Starting the example."

Next, the program in the main method will create an instance of the Student class by using the Student constructor. It will initialize gradeLevel to 10, name to "Bob Smith," age to 16, and assignment to null. With the creation of this object, the computer will move on to the next line of the main method. 

To print out bob, the program in the main method will use the toString() method of the Student class, which will return a String ("Bob Smith, a 10th grade high school student") that will then be printed.

Lastly, the program in the main method will print out "End of example."