AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

5.4 Accessor Methods

Verified for the 2025 AP Computer Science A examCitation:

Accessor methods are the windows into an object's state, allowing controlled access to an object's data without exposing the underlying instance variables. In Java's object-oriented paradigm, these methods play a crucial role in maintaining encapsulation while providing a way for other objects to retrieve information about an object. This section explores how non-void methods work, how they return values, and how special accessor methods like toString() help objects communicate their state to the outside world.

What Are Accessor Methods?

Accessor methods (commonly called "getters") are methods that:

  • Are declared with the public access modifier to allow access from outside the class
  • Allow other objects to obtain values of instance variables
  • Return a value to the caller using a return statement
  • Usually start with "get" followed by the variable name (e.g., getName())
  • Typically don't modify the object's state
  • Have a non-void return type
public class Student {
    private String name;
    private double gpa;
    
    // Constructor
    public Student(String name, double gpa) {
        this.name = name;
        this.gpa = gpa;
    }
    
    // Accessor methods
    public String getName() {
        return name;
    }
    
    public double getGPA() {
        return gpa;
    }
}

Non-void Methods and Return Types

Unlike void methods, non-void methods:

  • Specify a return type in their method header (instead of void)
  • Must include a return statement with a compatible value
  • Return control to the calling method after executing the return statement

A return statement consists of the return keyword followed by an expression whose value becomes the result of the method call. This statement immediately terminates method execution and sends the specified value back to wherever the method was called.

// Void method (no return value)
public void printInfo() {
    System.out.println("Name: " + name);
    System.out.println("GPA: " + gpa);
    // No return statement required
}

// Non-void method (returns a String)
public String getDescription() {
    return "Student: " + name + " with GPA " + gpa;
    // Must return a String (compatible with the return type)
}

Return Types

A method's return type can be:

  • A primitive type (int, double, boolean, etc.)
  • A reference type (String, array, or other object types)
  • The void keyword (for methods that don't return a value)
public boolean isHonorRoll() {
    return gpa >= 3.5;  // Returns a boolean value
}

public String[] getCourses() {
    return courses;  // Returns an array (reference type)
}

public Student getBestFriend() {
    return bestFriend;  // Returns a Student object (reference type)
}

Return by Value: How It Works

When a method returns a value, Java uses "return by value" semantics:

  1. The return expression is evaluated
  2. A copy of the value is created
  3. The copy is returned to the calling method

For primitive types, this means the actual value is copied. For reference types, the reference (not the object itself) is copied.

public int getAge() {
    return age;  // A copy of the int value is returned
}

public Student[] getClassmates() {
    return classmates;  // A copy of the array reference is returned
                        // (not a copy of the array itself)
}

Important Note About Reference Returns

When returning a reference to an object:

  • A copy of the reference is returned, not a copy of the object
  • The caller receives a reference to the same object, not a new object
  • Changes made through the returned reference will affect the original object
public class School {
    private ArrayList<Student> students;
    
    // CAUTION: This returns a reference to the actual list
    public ArrayList<Student> getStudentList() {
        return students;  // Returns a reference to the actual list
    }
    
    // Better approach: Return a copy to protect encapsulation
    public ArrayList<Student> getStudentListSafe() {
        return new ArrayList<Student>(students);  // Returns a copy
    }
}

The return Keyword

The return keyword serves two important purposes:

  1. It specifies the value to be returned to the caller
  2. It immediately ends the method execution and returns control to the caller
public double calculateFinalGrade(double participation, double homeworkAvg, 
                                  double midterm, double finalExam) {
    // Input validation
    if (participation < 0 || homeworkAvg < 0 || midterm < 0 || finalExam < 0) {
        return -1;  // Error code - method ends here if any grade is negative
    }
    
    // Calculate weighted average (only executed if all grades are valid)
    return participation * 0.1 + homeworkAvg * 0.4 + midterm * 0.2 + finalExam * 0.3;
}

The toString() Method

The toString() method is a special accessor method that:

  • Is declared with the public access modifier so it can be called from any class
  • Returns a String representation of an object
  • Contains a return statement that provides a textual description of the object
  • Is automatically called when an object is used in string concatenation or printed
  • Should be overridden in your classes to provide meaningful object descriptions

When overriding methods like toString(), it's best practice to use the @Override annotation. This annotation tells the compiler that you intend to override a method from a superclass or implement a method from an interface. If you make a mistake (like a typo in the method name or incorrect parameters), the compiler will catch the error.

public class Rectangle {
    private double length;
    private double width;
    
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }
    
    // Override the default toString() method
    @Override
    public String toString() {
        return "Rectangle [length=" + length + ", width=" + width + 
               ", area=" + (length * width) + "]";
    }
}

How toString() Is Used

The toString() method is called automatically in these contexts:

Rectangle rect = new Rectangle(5.0, 3.0);

// toString() is called automatically in these cases:
System.out.println(rect);                  // Prints: Rectangle [length=5.0, width=3.0, area=15.0]
System.out.println("My shape: " + rect);   // Prints: My shape: Rectangle [length=5.0, width=3.0, area=15.0]
String description = rect.toString();      // Explicitly calling toString()

Design Guidelines for Accessor Methods

GuidelineExample
Name accessors with "get" + variable namegetName(), getBalance()
Return the same type as the instance variablepublic double getBalance() for a double balance
Keep accessors simple – focused on returning dataAvoid complex logic in accessor methods
Consider returning copies of mutable objectsreturn new ArrayList<>(items) instead of return items
Include a toString() method in every classOverride Object's default toString()

Examples of Complete Accessor Methods

public class BankAccount {
    private String accountNumber;
    private String ownerName;
    private double balance;
    private ArrayList<Transaction> transactions;
    
    // Constructor omitted for brevity
    
    // Simple accessor methods
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public String getOwnerName() {
        return ownerName;
    }
    
    public double getBalance() {
        return balance;
    }
    
    // Accessor that returns a copy to protect the original
    public ArrayList<Transaction> getTransactionHistory() {
        return new ArrayList<>(transactions);
    }
    
    // Derived accessor (computes a value)
    public boolean isOverdrawn() {
        return balance < 0;
    }
    
    // toString method
    @Override
    public String toString() {
        return "Account #" + accountNumber + " | Owner: " + ownerName +
               " | Balance: $" + String.format("%.2f", balance);
    }
}

Key Points to Remember

  • Accessor methods provide controlled access to an object's internal state

  • Non-void methods must include a return statement with a value compatible with the return type

  • Java uses "return by value" - primitive values are copied, while for objects, references are copied

  • The toString() method provides a String representation of an object and is called automatically in string contexts

  • When returning mutable objects, consider returning copies to maintain encapsulation

  • When an object is passed to System.out.print or println, its toString() method is called automatically

Key Terms to Review (15)

Accessor Methods: Accessor methods, also known as getter methods, are a type of method in object-oriented programming that allows the retrieval of the value of an object's private data member. They provide read-only access to the internal state of an object.
Assignment Class: An assignment class refers to a class used to store values assigned to variables. It is commonly used in programming to hold and manipulate data.
Assignment constructor: An assignment constructor is a special type of constructor in object-oriented programming that initializes an object's instance variables with values provided by the user at the time of object creation.
CorrectAnswer: A correct answer refers to the accurate response to a question or problem in a given context.
Instance Variable: An instance variable is a variable that belongs to an object and holds unique data for each instance of the class. It is declared within a class but outside any method.
Name: The name refers to a unique identifier given to an entity, such as a variable or a method, in a programming language. It helps distinguish one entity from another.
Non-void methods: Non-void methods are functions in programming that return a value after performing a specific task or calculation.
@Override: The @Override annotation is used in Java to indicate that a method in a subclass is intended to override a method with the same name in its superclass. It helps ensure that the method signature and return type are correct.
Private Variables: Private variables are variables that can only be accessed and modified within the same class they are declared in. They provide encapsulation and help maintain data integrity by preventing direct access from other classes.
Public: Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.
Return Statement: A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.
Return Type: The return type in programming refers to the data type of the value that a method or function will return when it is called. It specifies what kind of data will be returned by the method.
String Concatenation: String concatenation is the process of combining two or more strings together into one longer string. It is achieved using the "+" operator in most programming languages.
Student class: A student class is a blueprint or template that defines the properties and behaviors of a student object. It specifies what data (such as name, grade level) and methods (such as calculateGPA()) a student object can have.
Student constructor: A student constructor is a specific type of constructor used to create objects representing students. It initializes instance variables related to student attributes such as name, age, grade level, etc., when creating new student objects.