Unit 3 Cycle 1 Day 1: Class Anatomy

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

Class Anatomy

Section 3.1 — Anatomy of a Class

Key Concept

A Java class is a blueprint that defines the state (instance variables) and behavior (methods) of objects. Every class has three core components: fields that store data, constructors that initialize new objects, and methods that define what objects can do. Instance variables are typically declared private to enforce encapsulation, while methods are declared public to provide controlled access. Understanding this anatomy is the foundation for all class design questions on the AP CSA exam.

Consider the following class declaration.

public class Dog { private String name; private int age; public Dog(String n, int a) { name = n; age = a; } public String getName() { return name; } }

Which of the following correctly creates a Dog object and prints its name?

Answer: (A) Dog d = new Dog("Rex", 5); System.out.println(d.getName());

Option A correctly uses new to create an object with two arguments matching the constructor, then calls the public accessor getName() to access the private field.

Why Not the Others?

(B) There is no zero-argument constructor, so new Dog() fails. Also, name is private and cannot be accessed directly.

(C) Missing the new keyword. Objects must be created with new ClassName(args).

(D) name is private. It cannot be accessed outside the class. Use getName() instead.

Common Mistake

Private instance variables cannot be accessed with dot notation outside the class. Always use accessor (getter) methods to read private data.

AP Exam Tip

On the AP exam, always check: (1) Is new used? (2) Do arguments match a constructor? (3) Are private fields accessed only through public methods?

Review this topic: Section 3.1 — Anatomy of a Class • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

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