Unit 3 Cycle 1 Day 1: Class Anatomy
Share
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.
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?