| Study Guides
AP · Writing Classes · 16 min read · Updated 2026-05-07

Writing Classes — AP Computer Science A CS A Study Guide

For: AP Computer Science A candidates sitting AP Computer Science A.

Covers: Class anatomy, static vs instance members, encapsulation with the private keyword, method overloading, and Java code documentation standards for AP CS A.

You should already know: Basic Java or any other procedural-language programming.

A note on the practice questions: All worked questions in the "Practice Questions" section below are original problems written by us in the AP Computer Science A style for educational use. They are not reproductions of past College Board papers and may differ in wording, numerical values, or context. Use them to practise the technique; cross-check with official College Board mark schemes for grading conventions.


1. What Is Writing Classes?

Writing classes is the core practice of object-oriented programming (OOP) in Java, where you define reusable blueprints for objects that bundle related data (called state or attributes) and behavior (called methods) into a single unit. This topic makes up 10-15% of the AP CS A exam, with most assessment occurring in free-response questions (FRQs) that ask you to write full or partial class implementations. Common synonyms for this skill include OOP class design, Java object blueprinting, and class implementation.

2. Class anatomy — fields, constructors, methods

Every Java class follows a standard structure with three core components, each serving a distinct purpose:

  1. Fields (Instance Variables): Variables declared inside the class that store the state of individual objects of the class. Each object gets its own copy of all instance fields.
  2. Constructors: Special methods that run automatically when an object is created with the new keyword. They have no return type (not even void) and must have exactly the same name as the class, including capitalization. Their only job is to initialize the fields of the new object. If you do not write any constructors, Java provides a default no-argument constructor that sets all fields to default values (0 for numbers, null for objects, false for booleans). If you write any custom constructor, the default no-arg constructor is no longer available unless you write it explicitly.
  3. Methods: Functions defined inside the class that define the behavior of objects. They can read or modify object state, take parameters, and return values.

Worked Example: Basic Student Class Anatomy

// Fields (state)
private String fullName;
private int studentID;
private double gpa;

// Constructor (initializes new objects)
public Student(String name, int id, double initialGPA) {
 fullName = name;
 studentID = id;
 gpa = initialGPA;
}

// Method (behavior: update GPA with validation)
public void setGPA(double newGPA) {
 if(newGPA >= 0.0 && newGPA <= 4.0) {
 gpa = newGPA;
 }
}

Exam tip: Examiners regularly deduct marks for mismatched constructor and class names, or adding a void return type to constructors. Double-check these details before moving on from a class writing FRQ.

3. Static vs instance members

Class members (fields and methods) are either instance or static, depending on whether they belong to individual objects or the class itself:

  • Instance members: Belong to individual objects. Each object has its own copy of instance fields, and you must call instance methods on an object reference. Instance methods can access both instance and static members of the class.
  • Static members: Belong to the class as a whole, not any individual object. Only one copy of a static field exists across all objects of the class, and static methods are called directly on the class name, no object required. Static methods can only access other static members, not instance fields or methods, as they have no reference to a specific object.

Worked Example: Static Member Usage

We extend the Student class to track total enrolled students:

// Static field: one copy across all Student objects
private static int totalStudents = 0;

// Updated constructor increments static count when new student is created
public Student(String name, int id, double initialGPA) {
 fullName = name;
 studentID = id;
 gpa = initialGPA;
 totalStudents++;
}

// Static method to access the static count
public static int getTotalStudents() {
 return totalStudents;
}

Usage of static vs instance members:

Student alice = new Student("Alice Smith", 101, 3.8);
Student bob = new Student("Bob Jones", 102, 3.5);
// Call instance method on object reference
System.out.println(alice.getGPA()); // Prints 3.8
// Call static method on class name, not object
System.out.println(Student.getTotalStudents()); // Prints 2

Exam tip: While Java allows calling static methods on object references, this is considered bad practice and will lose you marks on the exam. Always use the class name to call static methods.

4. Encapsulation with private

Encapsulation is a core OOP principle that restricts direct access to an object's internal state, so you can control how data is modified, prevent invalid state, and hide implementation details from outside code. The private access modifier makes a field or method only accessible from inside the class it is defined in. To let outside code safely read or modify private fields, you write public getter (accessor) methods to read values, and public setter (mutator) methods to modify values, with built-in validation to block invalid changes.

Worked Example: Encapsulated Student Name Field

// Private field: no direct access outside the class
private String fullName;

// Public getter: read access to fullName
public String getFullName() {
 return fullName;
}

// Public setter: controlled write access to fullName with validation
public void setFullName(String newName) {
 if(newName != null && !newName.isBlank()) {
 fullName = newName;
 }
}

If fullName was public, outside code could set it to an empty string or null, leading to invalid object state. Encapsulation eliminates this risk. Exam tip: 90% of class writing FRQs require all fields to be private. Leaving a field public will cost you at least 1 mark per field, with no exceptions.

5. Method overloading

Method overloading is the practice of defining multiple methods in the same class with the same name, but different parameter lists. Java uses the parameter list to determine which version of the method to run when it is called. A valid parameter list difference includes:

  1. A different number of parameters
  2. Different data types of parameters
  3. A different order of parameter types

The return type of the method does not count as part of the parameter list. Two methods with the same name and same parameter list but different return types will cause a compile error.

Worked Example: Overloaded GPA Update Methods

We add two overloaded updateGPA methods to the Student class for different use cases:

// Version 1: Directly set new GPA if valid
public void updateGPA(double newGPA) {
 if(newGPA >= 0.0 && newGPA <=4.0) {
 gpa = newGPA;
 }
}

// Version 2: Calculate new GPA from a new course grade and credit hours
public void updateGPA(int creditHours, double courseGrade) {
 double totalPoints = gpa * totalCredits + (courseGrade * creditHours);
 gpa = totalPoints / (totalCredits + creditHours);
 totalCredits += creditHours;
}

When you call updateGPA, Java automatically selects the correct version based on the arguments passed:

alice.updateGPA(3.9); // Uses version 1
alice.updateGPA(3, 4.0); // Uses version 2

The GPA calculation for version 2 follows the standard weighted average formula: Exam tip: Examiners regularly test the difference between overloading and overriding in multiple choice questions. Remember: overloading occurs in the same class with the same name and different parameters; overriding occurs in a subclass with the same name and identical parameters.

6. Documentation and comments

Clear documentation makes your code readable for other developers, and on the AP exam, well-placed comments can help you earn partial credit if your code contains small syntax or logic errors. Java supports three types of comments:

  1. Single-line comments: Use // for short notes explaining logic inside methods.
  2. Multi-line comments: Use /* ... */ for longer notes spanning multiple lines.
  3. Javadoc comments: Use /** ... */ for official documentation of classes, constructors, and methods. Javadoc comments use tags like @param to describe parameters, @return to describe return values, and @throws to describe exceptions the method may throw, and can be used to auto-generate official documentation pages.

Worked Example: Javadoc for Student Constructor

/**
 * Constructs a new Student object with the provided personal and academic details
 * @param name the full legal name of the student, cannot be blank
 * @param id the unique 3-digit student ID number, must be between 100 and 999
 * @param initialGPA the student's starting GPA, must be between 0.0 and 4.0
 */
public Student(String name, int id, double initialGPA) {
 // Implementation here
}

Exam tip: You are not required to write full Javadoc on the AP exam unless explicitly asked, but adding short single-line comments for non-obvious logic (e.g. validation rules) will help graders follow your reasoning and award partial credit for partially correct code.

7. Common Pitfalls (and how to avoid them)

  • Pitfall 1: Adding a return type (including void) to constructors, e.g. writing public void Student(...) instead of public Student(...). Why it happens: Students confuse constructors with regular methods, which always require a return type. Fix: Remember constructors have no return type at all, and their name must exactly match the class name, including capitalization.
  • Pitfall 2: Declaring fields as public instead of private, or forgetting to write getters/setters for required external access. Why it happens: Direct field access feels faster to write, or students forget private fields are not accessible outside the class. Fix: Default to making all fields private, and only add public getters/setters if the problem explicitly states outside code needs to read or modify the field.
  • Pitfall 3: Accessing instance fields in static methods, or calling static methods on object references. Why it happens: Students mix up which members belong to the class vs individual objects. Fix: Static methods can only access static fields and methods; always call static methods using the class name, not an object reference.
  • Pitfall 4: Trying to overload methods by only changing the return type, e.g. public int getScore() and public double getScore() with identical parameter lists. Why it happens: Students incorrectly assume return type is part of the method signature for overloading. Fix: Overloading only depends on parameter lists: number, type, and order of parameters. Identical parameter lists with different return types cause a compile error.
  • Pitfall 5: Assuming Java provides a default no-arg constructor after you write a custom constructor with parameters. Why it happens: Students forget the default constructor is only available if no custom constructors are defined. Fix: If you need a no-arg constructor for your class, write it explicitly if you have defined any other constructors.

8. Practice Questions (AP Computer Science A Style)

Question 1

Write a full class definition for a Book class that meets all of the following requirements:

  1. Private fields for title (String), author (String), pageCount (int), and isAvailable (boolean, indicates if the book can be checked out)
  2. A constructor that takes 3 parameters: title, author, page count, and initializes isAvailable to true
  3. A method checkOut() that sets isAvailable to false only if it is currently true, and returns true if the checkout was successful, false otherwise
  4. A method checkIn() that sets isAvailable to true
  5. A getter method for the isAvailable field

Solution

public class Book {
 // Private fields
 private String title;
 private String author;
 private int pageCount;
 private boolean isAvailable;

 // Constructor
 public Book(String t, String a, int pages) {
 title = t;
 author = a;
 pageCount = pages;
 isAvailable = true;
 }

 // checkOut method
 public boolean checkOut() {
 if(isAvailable) {
 isAvailable = false;
 return true;
 }
 return false;
 }

 // checkIn method
 public void checkIn() {
 isAvailable = true;
 }

 // Getter for isAvailable
 public boolean getIsAvailable() {
 return isAvailable;
 }
}

All fields are private, the constructor matches the class name with no return type, and all methods implement the required logic with correct return types.


Question 2

For each new member added to the Book class, identify if it should be static or instance, and justify your answer: a) A field that tracks the total number of Book objects added to the library system b) A method that returns the title of the current book c) A method that returns the total number of Book objects in the system

Solution

a) Static: There is only one total count across all books, so it belongs to the class as a whole, not individual book objects. b) Instance: Each book has its own unique title, so the method must access the instance field of a specific book object. c) Static: The method accesses the static total count field, so it belongs to the class, not individual objects.


Question 3

Which of the following pairs of methods are valid overloaded methods in the same class? For invalid pairs, explain why they are invalid. a) public void calculate(int x) and public int calculate(int y) b) public void print(String s) and public void print(int i) c) public double findArea(double r) and public double findArea(double l, double w)

Solution

a) Invalid: The parameter lists are identical (both take one integer parameter). Only the return type differs, which is not sufficient for overloading. This will cause a compile error. b) Valid: The methods have the same name, and different parameter types (String vs int), so they are properly overloaded. c) Valid: The methods have the same name, and a different number of parameters (1 vs 2 double parameters), so they are properly overloaded.

9. Quick Reference Cheatsheet

Concept Core Rule
Class Anatomy Fields store object state, constructors initialize new objects (no return type, match class name exactly), methods define object behavior
Instance Members Belong to individual objects, accessed via object reference, each object has its own copy
Static Members Belong to the class, accessed via class name, only one copy exists across all objects
Encapsulation All fields should be private; use public getters/setters for controlled access with validation
Method Overloading Same method name, different parameter list (number, type, order of parameters); return type does not count
Documentation Use // for single-line internal comments, /** ... */ Javadoc with @param/@return tags for public class/method docs
Exam Rules No return type for constructors, never use public fields, call static methods on the class name

10. What's Next

Writing classes is the foundation for all remaining object-oriented programming content in the AP CS A syllabus, including inheritance, polymorphism, abstract classes, and interfaces, which make up an additional 15-20% of the exam. You will also use class writing skills for almost every FRQ on the exam, including questions that require you to implement classes to work with arrays, ArrayLists, 2D arrays, and recursion-based problems. Strong class writing skills will also help you quickly understand and debug code snippets in multiple choice questions.

If you have any questions about class syntax, access modifiers, overloading rules, or FRQ grading conventions, you can ask Ollie, our AI tutor, for personalized explanations and extra practice problems at any time. You can also find more study guides, full-length practice tests, and FRQ grading rubrics on the homepage to build your confidence ahead of the AP CS A exam.

← Back to topic

Stuck on a specific question?
Snap a photo or paste your problem — Ollie (our AI tutor) walks through it step-by-step with diagrams.
Try Ollie free →