Unit 3 Cycle 1 Day 24: Writing a Complete Class
Share
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.
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.