Anatomy of a
Java Class
Understand the building blocks of every Java program: classes, fields, constructors, and methods that work together as a blueprint for objects.
What Is a Class?
A class is a blueprint or template that defines the attributes (data) and behaviors (actions) an object can have. Think of it like an architectural plan: the plan itself is not a house, but every house built from it shares the same structure.
Classes vs Objects
Why Classes Matter
The Four Parts of a Class
Instance Variables: The Data
Instance variables (also called fields) store the state of each object. Every object gets its own independent copy.
One ticket office counter, many fixed ticket IDs
Separate tickets provide an analogy for separate objects. In the Dog example, each instance has its own name and age fields.Each object keeps its own state
Suppose two Dog instances store Milo, age 2, and Luna, age 4. Each name and age belongs to its own instance. Changing one object’s fields does not automatically change the other object.Constructors: Building Objects
A constructor is a special method that initializes a new object. It has the same name as the class and no return type.
Methods: The Behavior
Methods define what an object can do. They can return values (accessor methods) or change the object's state (mutator methods).
public vs private
| public | private | |
|---|---|---|
| Visible to | Any class | Only the declaring class |
| Used for | Constructors, methods | Instance variables |
| Why | Provide controlled access | Enforce encapsulation |
| AP Exam default | Methods & constructors | All instance variables |
The this Keyword
When a parameter name matches an instance variable name, Java needs a way to tell them apart. The keyword this refers to the current object.
The toString Method
Every class in Java inherits a toString() method from Object. You override it to return a human-readable String describing the object.
Complete Example: Student Class
Using the Student Class
How to Write a Class
Common Mistakes to Avoid
Class Anatomy Summary
| Component | Purpose | Key Rule |
|---|---|---|
| Instance Variables | Store object state | private |
| Constructor | Initialize new objects | Same name as class, no return type |
| Accessor Method | Return field values | Has a return type, no side effects |
| Mutator Method | Modify field values | Usually returns void |
| toString() | String representation | Called automatically by println |
Question 1 of 5
Which of the following is true about constructors in Java?
Question 2 of 5
Consider the following class:
What does System.out.println(new Pet("Max", 3)) print?
Question 3 of 5
What is the primary purpose of declaring instance variables as private?
Question 4 of 5
Which type of method changes the value of an instance variable?
Question 5 of 5
Consider the following code segment:
What happens when the last line executes?