Unit 3 Cycle 1 Day 24: Writing a Complete Class

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

Writing a Complete Class

Section 3.6 — Writing Methods

Key Concept

Writing a complete class from scratch requires combining all class design elements: private instance variables, overloaded constructors with proper initialization, accessor methods that return state, mutator methods that validate and change state, and utility methods that perform calculations. The AP exam's free-response questions frequently require writing a complete class. The key is following encapsulation principles: make fields private, provide only necessary public methods, and validate input in mutators and constructors.

A GradeBook class stores a student name and list of scores. Consider the following partial class.

public class GradeBook { private String name; private int[] scores; public GradeBook(String n, int[] s) { name = n; scores = s; } public double average() { int sum = 0; for (int score : scores) { sum += score; } return (double) sum / scores.length; } }

What does new GradeBook("Al", new int[]{90, 80, 70}).average() return?

Answer: (A) 80.0

sum = 90+80+70 = 240. (double) 240 / 3 = 80.0. The cast to double ensures decimal division.

Why Not the Others?

(B) The return type is double due to the cast. 80.0, not 80.

(C) 240 is the sum, not the average.

(D) 240.0 is the sum cast to double, not divided by the count.

Common Mistake

Without the cast (double), integer division would give 240/3=80 (an int). The cast ensures floating-point division, returning 80.0.

AP Exam Tip

When computing averages, always cast to double before dividing: (double) sum / count. This is a critical detail on the AP exam FRQs.

Review this topic: Section 3.6 — Writing Methods • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

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