Lesson 3.3: Anatomy of a Class

Unit 3 · Lesson 3.3 · Code Mechanics

Lesson 3.3: Anatomy of a Class

🕑 30–35 min· 8 Practice Questions· 4 Mastery Questions· Output Predictor + Bug Hunt

What You'll Learn

  • Identify all components of a Java class
  • Write correct accessor and mutator methods
  • Apply public and private access modifiers correctly
  • Recognize common accessor/mutator errors on the AP exam

Key Vocabulary

Term Definition
class header First line of a class definition; includes access modifier, class keyword, and class name
instance variable Private attribute defined in the class body, outside any method; each object has its own copy (EK 3.3.A.1)
accessor (getter) Method that returns the value of a private instance variable without modifying it (EK 3.3.A.3)
mutator (setter) Void method that modifies the value of a private instance variable (EK 3.3.A.4)
encapsulation Bundling private data with public methods that control access (EK 3.3.A.5)
public Access modifier: the member can be accessed by any class
private Access modifier: the member can only be accessed within its own class (EK 3.3.A.5–3.3.A.6)

CED EK 3.3.A.1–3.3.A.6

A class contains private instance variables (EK 3.3.A.1), accessor methods for read access (EK 3.3.A.3), and mutator methods for write access (EK 3.3.A.4). Instance variables should be private (EK 3.3.A.5). Public methods are accessible anywhere; private methods only inside the class (EK 3.3.A.6).

Complete Class Anatomy

public class Rectangle {                   // class header
    private double width;                  // instance variable
    private double height;

    public Rectangle(double w, double h) { // constructor
        width = w; height = h;
    }

    public double getWidth()  { return width;  }  // accessor
    public double getHeight() { return height; }

    public void setWidth(double w) {            // mutator
        if (w > 0) width = w;
    }

    public double getArea() { return width * height; } // behavior
}

Accessor Methods: Rules

Standard Accessor Pattern

public String getName() {
    return name;
}

Convention: get + capitalized variable name. Return type must match the variable type. NEVER modifies the variable.

Mutator Methods: Rules

Standard Mutator Pattern

public void setName(String n) {
    name = n;
}

Almost always void. Takes a parameter of the variable's type. Can include validation.

Access Modifier Summary

Member Typical Modifier
Instance variables private -- protects state (EK 3.3.A.5)
Constructor public -- allows object creation from outside
Accessor methods public -- external read access
Mutator methods public -- external write access (controlled)
Helper methods private -- internal use only

AP Trap: Getter Must NOT Modify State

// WRONG
public int getCount() { return count++; }

A getter that modifies a variable violates the accessor contract. The AP exam shows this pattern and asks why it is incorrect.

AP Trap: Return Type Must Match

If balance is a double, the getter MUST return double, not int.

AP Trap: Setter Should Be void

// WRONG
public int setAge(int a) { age = a; return age; }
// CORRECT
public void setAge(int a) { age = a; }

Setters typically return void. Returning a value from a setter is non-standard and a common distractor.

AP Trap: Accessing Private Variable Externally Is a Compile Error

// In another class:
myAccount.balance = 10000.0;  // COMPILE ERROR

Private restricts external access. This is a compile-time error, not a runtime exception.

Real-World Connection: A thermostat exposes a public interface (setTemperature(), getCurrentTemp()) while keeping sensor calibration private.

Summary

  • A class has a header, private instance variables, constructors, and methods.
  • Instance variables should always be private (EK 3.3.A.5).
  • Accessors return variable values and must NOT change state.
  • Mutators are typically void and modify a private variable.
  • Public methods accessible anywhere; private methods only inside the class (EK 3.3.A.6).
  • Return type of a getter must exactly match the type of the variable it returns.
Tier 2 · AP Practice

Practice Questions

MCQ 1
Which correctly classifies the methods?
public boolean isOn()  { return isOn; }
public void turnOn()   { isOn = true; }
A isOn() is mutator; turnOn() is accessor
B isOn() is accessor; turnOn() is mutator
C Both are accessors
D Both are mutators
B is correct. isOn() returns without modifying -- accessor. turnOn() changes state -- mutator.
MCQ 2
The following getter is flawed. What is wrong?
public int getScore() { score += 10; return score; }
A Accessors must return void
B Accessors should not return primitives
C The return type should be String
D An accessor should NOT modify the instance variable it reads
D is correct. Every call to getScore() adds 10 as an unexpected side effect.
MCQ 3
For private double reading;, which is the CORRECT mutator?
A public double setReading(double r) { reading = r; return reading; }
B private void setReading(double r) { reading = r; }
C public void setReading(double r) { reading = r; }
D public void getReading(double r) { reading = r; }
C is correct. Standard mutator: public, void, correct parameter type.
MCQ 4
For private String title;, which accessor is CORRECT?
A public void getTitle() { return title; }
B public String getTitle() { return title; }
C public String getTitle() { title = ""; return title; }
D private String getTitle() { return title; }
B is correct. Returns correct type, doesn't modify state, is public.
MCQ 5
The following class will NOT compile. Identify the error.
public class Box {
    private int length; private int width;
    public void setLength(int l) { length = l; }
    public int getLength() { return length; }
    public int getArea() { return length * width; }
}
⚠ Predict the answer before reading the options.
A getArea() cannot access private variables
B Missing constructor prevents compilation
C setLength() has the wrong return type
D This class compiles without errors
D is correct. All parts are valid: private fields accessible inside the class, default constructor provided by Java, void setter correct.
MCQ 6
In another class: myAccount.balance = 10000.0; where balance is private. Result?
A Succeeds because balance is a double
B Succeeds but getBalance() returns old value
C Compile-time error: balance is private
D Runtime exception: balance is read-only
C is correct. Accessing a private field from outside the class is a compile-time error in Java.
MCQ 7
Which is the BEST example of a method that should be private?
A A constructor that creates a new object
B A helper that validates input before a mutator assigns it, not meant for external callers
C A method that prints the object state to the console
D A method that returns an instance variable
B is correct. Internal validation helpers are implementation details -- private keeps them hidden from external callers.
MCQ 8
I. Instance variables should be private
II. The constructor should be public
III. Accessor methods should be public void
Which are TRUE?
A I only
B I and II only
C II and III only
D I, II, and III
B is correct. I and II are standard OOP anatomy. III is false: accessors return the variable's type, NOT void.
PRACTICE WITH A GAME — CHOOSE ONE:
Output Predictor: Accessor and Mutator Calls
Predict what each segment prints.
Question 1 of 3  ·  Score: 0

Done!
You got 0 of 3 correct.
Bug Hunt: Class Anatomy
Click the buggy line, or 'No bug'.
Question 1 of 3  ·  Score: 0
No bug — code is correct
Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: Anatomy of a Class

MCQ 1
The following class has a critical encapsulation error. Which line?
public class Patient {
    public String name;
    private int age;
    public Patient(String n, int a) { name = n; age = a; }
    public String getName() { return name; }
}
A Line 3: age should be public
B Line 4: the constructor should be private
C Line 2: name should be private, not public
D Line 5: getName() should return void
C is correct. name is public, breaking encapsulation. Any code can directly overwrite it.
MCQ 2
Which BEST describes the relationship between a private instance variable and its accessor?
A The accessor allows external classes to read the variable's value without directly accessing it
B The accessor allows external classes to modify the variable
C The accessor and variable must have the same access modifier
D A private variable can only have one accessor
A is correct. The accessor provides controlled, read-only external access.
MCQ 3
Which change makes this class compile AND follow correct OOP anatomy?
public class Bottle {
    private String liquid;
    private void Bottle(String l) { liquid = l; }
    public String getLiquid() { return liquid; }
}
A Change getLiquid() to return void
B Change private String liquid to public
C Change 'private void Bottle' to 'public Bottle' -- removing void
D Add static before String liquid
C is correct. Two constructor issues: void makes it a regular method; private prevents external construction.
MCQ 4
For private int temperature;, which accessor/mutator pair is CORRECTLY defined?
A public void getTemp() with return + public int setTemp(int t)
B public int getTemp() { return temperature; } + public void setTemp(int t) { temperature = t; }
C public int getTemp() { temperature++; return temperature; } + void setter
D private int getTemp() { return temperature; } + void setter
B is correct. Accessor returns int (matches), doesn't modify state. Mutator is public void. A: void getter won't compile with return. C: getter modifies. D: getter is private.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]