APrep Open the app

AP Computer Science A · Unit 3: Class Creation

3.4 Accessor Methods

What accessor methods do

An accessor method returns information about the state of an object without changing it. Often called getter methods, they typically start with `get` (e.g., `getAge()`) and have a return type matching the instance variable they retrieve. They allow controlled, read-only access to private data.

Why encapsulation matters

Instance variables are usually declared private to protect them from direct outside access. Accessor methods provide a safe, public way to read that data. This is part of encapsulation — hiding internal implementation details while exposing only what's necessary through a well-defined interface.

Writing an accessor method

A typical accessor has a public access modifier, a return type matching the variable, no parameters, and a `return` statement. Example: `public int getAge() { return age; }`. Boolean accessors often use `is` instead of `get`, like `isEmpty()`.

Key terms

Accessor method
A method that returns the value of an instance variable without modifying it; also called a getter.
Typical accessor naming
Starts with 'get' for most types (e.g., getName()) or 'is' for booleans (e.g., isActive()).
Encapsulation
Hiding an object's internal data (private variables) and exposing controlled access via public methods.
Accessor method structure
Public access modifier, return type matching the variable, no parameters, and a return statement.
Why make instance variables private?
To protect data from unauthorized direct access/modification, allowing access only through defined methods like accessors.

Try an AP-style question

What does an accessor (getter) method do?

  1. Changes an instance variable
  2. Returns an instance variable's value
  3. Deletes the object
  4. Prints the class name
Show the answer

B. Read access.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 3.4 free in APrep