Unit 3 Cycle 1 Day 4: Accessor Methods

Unit 3 Foundation (Cycle 1) Day 4 of 28 Foundation

Accessor Methods

Section 3.4 — Accessor Methods

Key Concept

Accessor methods (getters) return the value of a private instance variable without modifying the object's state. By convention, they are named getFieldName() and take no parameters. The return type must match the field type. Accessor methods enforce encapsulation by allowing read-only access to private data. On the AP exam, accessor methods may perform calculations rather than simply returning a field: getFullName() might return firstName + " " + lastName. The key rule is that accessors do not change any instance variables.

Consider the following class.

public class BankAccount { private double balance; public BankAccount(double initial) { balance = initial; } public double getBalance() { return balance; } public boolean isOverdrawn() { return balance < 0; } }

Which of the following is a valid accessor method in the class above?

Answer: (A) getBalance() and isOverdrawn() are both accessors

Both methods return information about the object's state without modifying it. getBalance() returns the balance. isOverdrawn() returns a boolean derived from the balance. Neither changes any instance variable.

Why Not the Others?

(B) isOverdrawn() is also an accessor. It returns data about the object without modifying state.

(C) getBalance() is also an accessor. It returns the value of an instance variable.

(D) Both methods are accessors because they return values and do not modify the object.

Common Mistake

An accessor method reads and returns data but does not modify the object. Accessor methods can return instance variables directly OR return computed values (like boolean conditions).

AP Exam Tip

Accessor = reads only. Mutator = modifies state. If a method has a return type and no assignments to instance variables, it is an accessor.

Review this topic: Section 3.4 — Accessor Methods • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.