📚Study Guide: Writing Classes
Unit 5: Writing Classes
Object-oriented programming (OOP) revolves around classes, the blueprints from which objects are created. This unit teaches students to design and implement their own classes, encapsulating data (instance variables or fields) and behavior (methods). A well-designed class uses access modifiers to enforce encapsulation: instance variables are typically private, while methods are public, controlling how external code interacts with the object's state. Constructors initialize new objects, and multiple constructors can be provided through overloading as long as their parameter lists differ. The this keyword resolves ambiguity between instance variables and parameters with the same name. The AP exam heavily tests class design, often presenting a class skeleton and asking students to implement methods that manipulate instance variables. Students must understand the difference between instance variables (belonging to each object) and static variables (belonging to the class). Method signatures, return types, and parameter passing (pass-by-value) are critical concepts. When a reference type is passed to a method, the method receives a copy of the reference, so changes to the object's state persist, but reassigning the reference inside the method does not affect the original variable. Documentation through comments and clear naming conventions are expected in free-response questions.
Key Concepts
- Class Structure: A class contains fields (instance variables), constructors, and methods. Syntax: public class ClassName { private Type field; public ClassName(params) { ... } public returnType methodName(params) { ... } }
- Encapsulation: Private fields prevent direct external modification. Public accessor (getter) and mutator (setter) methods provide controlled access. This maintains data integrity and allows validation.
- Constructors: Special methods with the same name as the class, no return type, called with new. Overloaded constructors provide multiple ways to initialize an object. this() calls another constructor in the same class.
- The this Keyword: Refers to the current object. this.fieldName distinguishes instance variables from local variables or parameters with the same name. this(parameters) calls another constructor.
- Static vs. Instance: Static members belong to the class and are shared among all instances (e.g., Math.PI). Instance members belong to each individual object. Static methods cannot access instance variables directly.
- Pass-by-Value: Java passes primitive values by copying the value. Java passes reference variables by copying the reference address. The method can modify the object's state through the reference but cannot change the caller's reference variable itself.
Vocabulary
- Encapsulation: The OOP principle of bundling data and methods that operate on that data within a single unit (class) and restricting direct access to some components.
- Instance Variable (Field): A variable declared inside a class but outside any method; each object has its own copy.
- Accessor (Getter): A public method that returns the value of a private instance variable.
- Mutator (Setter): A public method that modifies the value of a private instance variable, often with validation logic.
- Constructor Overloading: Defining multiple constructors in the same class with different parameter lists to provide flexible object initialization.
- Shadowing: When a local variable or parameter has the same name as an instance variable, hiding the instance variable within that scope unless accessed with this.
Essential Formulas / Syntax Patterns
- public class Circle { private double radius; public Circle(double r) { radius = r; } public double getArea() { return Math.PI * radius * radius; } }
- this.radius = radius; // resolves shadowing
- public static final double TAX_RATE = 0.07; // class constant
Common Mistakes
- Returning Instead of Modifying: In setter methods, remember to assign the parameter to the instance variable: this.field = param; not just param = param;
- Confusing Static and Instance: Static methods belong to the class and cannot use this or access instance variables unless they have an object reference.
- Constructor Has a Return Type: Writing public void ClassName() creates a method, not a constructor. Constructors have NO return type.
- Expecting Pass-by-Reference Behavior: Reassigning a reference parameter inside a method (obj = new Object()) does NOT change the original reference variable in the caller.
AP Exam Strategies
- Design Classes Before Coding: List the instance variables, constructors, and methods needed. Decide what should be private vs. public.
- Use Meaningful Names: Name classes with nouns (Student), methods with verbs (calculateGPA), and boolean methods with is/has (isPassing).
- Always Provide toString: Although not required for the AP exam, a toString method makes debugging easier by printing object state.
- Check for Null: If a method accepts an object reference, consider whether null is a valid input and handle it gracefully to avoid NullPointerException.
Real-World Applications
- Banking Software: Account classes encapsulate balance, account number, and transaction history, exposing only safe operations like deposit and withdraw.
- Game Development: Player, Enemy, and Item classes model game entities with properties (health, position) and behaviors (move, attack, use).
- E-Commerce Platforms: Product, Cart, and Order classes represent domain entities, with encapsulation ensuring that prices and inventory counts remain consistent.