FRQ Type 2: Class Design
Practice these in the app
The second free-response question asks you to write a whole class: its header, its instance variables, a constructor, and a method. You get a description of what the class does, a table of example calls with the value each one returns, and sometimes a provided class that the new one uses.
It is always the second of the exam's four free-response questions: one class with one constructor and one method, worth 7 of their 25 points.
Reading the description and the table
The table lists statements in the order they run, the value each call returns (blank when there is none), and an explanation. Read it as part of the specification. The explanations state rules the description only hints at, and they show values the class has to remember between calls even though no parameter carries them.
- Each constructor call shows the constructor's parameter list. Its types decide the header.
- Each method call shows the method's name, its parameter, and what it returns. A return value such as
87.5means adouble; a value in quotes means aString. - A second object built partway through the table is there to show that each object keeps its own state. Its calls never change the first object's answers.
- A row that repeats a call and gets the same answer shows that the method only reports and changes nothing.
The skeleton
The examples on this page use a class for a slide at a water park. Here is its skeleton: the header, the instance variables, and a constructor that stores its parameters.
public class WaterSlide
{
private String slideName;
private int heightMeters;
private int rides;
private int totalSeconds;
private int fastestSeconds;
public WaterSlide(String name, int height)
{
slideName = name;
heightMeters = height;
rides = 0;
totalSeconds = 0;
fastestSeconds = 0;
}
}The constructor is where most skeleton points are lost. Writing
int heightMeters = height; inside it declares a new local variable that disappears when the constructor ends, and the instance variable stays 0. The 2026 guide denied the constructor point for this even when the local was marked private. When a parameter has the same name as the instance variable, heightMeters = heightMeters; assigns the parameter to itself. Write this.heightMeters = heightMeters;, or give the parameter a different name.Give every instance variable its starting value in the constructor, including the ones no parameter mentions. Java would start an
int at 0 anyway, but a value such as a starting amount that equals the capacity has to be set by hand, and writing all of them out shows the reader you thought about each.Hidden state
The parameters rarely tell you every instance variable you need. A
WaterSlide is built from a name and a height, but answering "what is the fastest ride so far" requires remembering the fastest time, and an average requires a running total and a count. Past questions have needed a count of days that met a goal, the team whose turn it is, and the strings a method had already handed out. Each came from the table and the explanations, not from a parameter.Anything a method must remember from one call to the next has to be an instance variable. A count declared inside the method starts over at 0 on every call, so the answer is right the first time and wrong after that. And an instance variable marked
static is shared by every object of the class, which shows up in the first object's next call after a second object is built.Update-and-return methods
The 2026 method changed the object and returned its new state in the same call. The order is the same each time: change the instance variables, apply any rule to the new values, then return the value the table shows, computed from the new state.
/** Records one ride that took seconds and returns the fastest
* ride so far, in seconds */
public int recordRide(int seconds)
{
rides++;
totalSeconds += seconds;
if (rides == 1 || seconds < fastestSeconds)
{
fastestSeconds = seconds;
}
return fastestSeconds;
}Rides of 34, 28, and 30 seconds return 34, 28, and 28. The first ride is always the fastest so far, which is what
rides == 1 handles. Without it, fastestSeconds would stay 0, since no time is less than 0. Returning seconds instead of fastestSeconds gives the right answer for the first two calls and the wrong one for the third.An average needs a cast. The fields
totalSeconds and rides are both int, so totalSeconds / rides drops the fraction: 92 seconds over 3 rides gives 30, not 30.666666666666668. Cast first, and handle the case with no data, which a table usually shows:public double averageSeconds()
{
if (rides == 0)
{
return 0.0;
}
return (double) totalSeconds / rides;
}Thresholds, percentages, and limits
Many classes change what they do once a value crosses a line. The rule turns on a single word: "less than" is
<, "at most" is <=, "at least" is >=, and "more than" is >. Check it against the table row where the value lands exactly on the line, if there is one.The description also says when the test happens. In 2026 a bottle was refilled when the amount left after a use would fall below 25% of its capacity, so the test used the amount after the subtraction, and an amount of exactly 25% stayed as it was. Testing the amount the bottle held before the use misses the use that takes it below the line: in the 2026 table, the third call returns 200.0 instead of 1000.0, and the refill waits for the next call.
A percentage has to keep its fraction. Suppose the water slide posts a ride time of 40 seconds, kept in a field
postedSeconds, and a ride counts as slow when it takes more than 125 percent of the posted time, that is, more than 50 seconds. Here are three ways to write the test for a 45-second ride:seconds > postedSeconds * 1.25 // 45 > 50.0 is false: right
seconds * 100 > postedSeconds * 125 // 4500 > 5000 is false: right
seconds > postedSeconds * (125 / 100) // 45 > 40 is true: wrongThe first line works in
double, and the second stays in int by moving the 100 to the other side. In the third, 125 / 100 is integer division, which gives 1, so every ride longer than the posted time counts as slow. The same mistake writes 25 percent as 25 / 100, which is 0. When the percentage is a parameter, divide by 100.0, not 100.Read whether a rule sets a field to a value or changes it by an amount. A field set to a value is assigned with
=, whatever it held before; a field changed by an amount uses += or -=. The 2026 bottle was filled to its capacity, so the refill was amount = capacity;, and adding the capacity to what was left would have overfilled it. A count that "starts over" is set to 0.Some fields must stay inside a limit. A value that is capped takes the smaller of the two, with
Math.min(value, cap) or an if, and a value with a floor takes the larger, with Math.max. Unless the description says a refusal costs something, a change that the rule refuses leaves every field as it was, and the method still returns what the table shows for that call. Make the test before changing anything, so a refused call never leaves half its changes behind.Building a String from state
Several classes have returned a String built from their instance variables, such as a score with hyphens between its parts or a name joined to an initial. Copy every literal piece of the table's examples exactly: the hyphens, spaces, and commas are part of the answer, and leaving one out has cost the point. A number joins a String with
+, and a double prints with its decimal point, so 12.0 appears as 12.0, not 12.public String getLabel()
{
return slideName + ", " + heightMeters + " m";
}For a slide built with
new WaterSlide("Blue Twister", 12), getLabel() returns "Blue Twister, 12 m". A method like this only reports, so calling it twice gives the same String both times.The method can also take a stored String apart. In 2023 it cut a message into lines of a given width with
substring and joined them with semicolons, and in 2025 it used indexOf to tell whether a signature sat at the start, at the end, or nowhere in a String. Points went to calling String methods such as substring, length, and indexOf with the right arguments and to handling every case, including an empty String. These are the same String methods as in the first free-response question.Two constructors
A class can have two constructors with different parameter lists. The shorter one fills in a default for what it doesn't receive. The 2018 question had a constructor with three parameters and one with a single parameter that used fixed values for the other two.
/** A slide whose height is not given is 10 meters tall */
public WaterSlide(String name)
{
slideName = name;
heightMeters = 10;
rides = 0;
totalSeconds = 0;
fastestSeconds = 0;
}Both headers have to match the table, and each constructor has to set every instance variable, since only one of them runs for a given object.
Objects inside the class
Some questions provide a class and ask you to write one that holds objects of it. In 2021, a combined restaurant table held two single tables. The instance variables are then references to those objects, and the methods call the provided class's methods on them. Here
WaterSlide plays the provided class, with an accessor getFastestSeconds() that returns fastestSeconds.public class SlidePair
{
private WaterSlide first;
private WaterSlide second;
public SlidePair(WaterSlide a, WaterSlide b)
{
first = a;
second = b;
}
/** Returns the faster of the two slides' fastest rides
* Precondition: each slide has been ridden at least once */
public int bestTime()
{
return Math.min(first.getFastestSeconds(), second.getFastestSeconds());
}
}The method asks each slide for its fastest time when it is called. Copying the times into instance variables in the constructor would freeze them, and later rides on either slide would never reach the pair. In 2021 the table changed a single table's view after the combined table was built, and a response that had stored the old value lost a point.
Comparing with another object of the class
A method can take a parameter of its own class. Inside the class, Java lets it read that object's private instance variables directly:
public boolean isTallerThan(WaterSlide other)
{
return heightMeters > other.heightMeters;
}In 2022 such a method compared two books' titles with
equals and their editions with >=. Compare Strings with equals, never ==.Scoring notes
- In 2026 the seven points were, in order: the class header, the private instance variables, the constructor header, the constructor storing its parameter, the method header, the algorithm, and the return. Only the sixth is an algorithm point.
- The narrow points survive mistakes elsewhere. In 2026 the return point was still earned with a wrong amount returned, and the instance variable point with the capacity declared as an
intinstead of adouble. - The algorithm point needs every step: update the instance variable, apply the rule to the new value, and keep the result. In 2026 it was lost for computing the right amount without storing it in the instance variable, and for computing it and then returning something else.
- Printing the answer instead of returning it, or as well as returning it, cost the return point in 2026. The algorithm point, which checks the update, was still earned.
publicmay be left off the class and the constructor, but not the method: in 2026 a method header withoutpubliclost its point.- Extra methods and extra instance variables cost nothing in themselves. Apart from the 2022 subclass, which lost a point for redeclaring its superclass's variables, the one extra instance variable that has cost a point is a copy of a value that can change, made in the constructor (2021).
- Since 2026 there are no separate penalty deductions. Errors that used to be penalties, such as returning a value from a constructor, now cost the point of the row they break.
- The general rules ignore small slips: spelling or capitals that leave no doubt, a missing semicolon or brace where the indentation shows the structure, and different parameter names.
Common traps
- Parentheses in the class header, as in
public class WaterSlide(). - An instance variable that is
public,static, or declared inside the constructor. - A return type on the constructor.
public void WaterSlide(String name)is a method, not a constructor. - Assigning the instance variable to the parameter,
height = heightMeters;, instead of the parameter to the instance variable. - A parameter with the same name as the instance variable and no
this.in front of the instance variable. - A hard-coded number where the class should use the value it stored. The table's second object, built with a different value, exposes it.
- A value the method must remember, declared as a local variable inside the method.
return amount - used;with no change to the instance variable, so the next call starts from the old amount.<where the rule says "at most," or a rule applied to the old value when the description tests the new one, or the other way round.- Integer division where the answer is a
double, including(25 / 100) * capacity, which is always 0. - A field changed by an amount where the rule sets it to a value, as in
amount += capacity;for a refill to capacity. - A refused change that updates some fields before the test that refuses it.
- A String built without one of the table's literal pieces, or with an extra separator at the end.
==on Strings.
A full question
The parameter gives the number between cleanings. The table shows a second value the class must remember, the shots since the last cleaning, which no parameter carries. Both become private instance variables:
public class EspressoMachine
{
private int cleanEvery;
private int shotsSinceCleaning;
public EspressoMachine(int every)
{
cleanEvery = every;
shotsSinceCleaning = 0;
}
public int brew(int shots)
{
shotsSinceCleaning += shots;
while (shotsSinceCleaning >= cleanEvery)
{
shotsSinceCleaning -= cleanEvery;
}
return cleanEvery - shotsSinceCleaning;
}
}The loop takes away one full set of shots for each cleaning. The row with
cafe.brew(23) needs two cleanings in one call: an if in place of the while takes away only 10, leaves 13, and returns -3. The row with cafe.brew(1) lands exactly on the limit, and the word "reaches" means >=; with > the method returns 0 there instead of 10. The two lines shotsSinceCleaning = (shotsSinceCleaning + shots) % cleanEvery; and return cleanEvery - shotsSinceCleaning; do the same job with %.A scoring guide for this question, written in the style of the 2026 guidelines, could read:
| Point | Earned for | Notes |
|---|---|---|
| 1 | Class header public class EspressoMachine | Not earned with parentheses in the header or code outside the class |
| 2 | Private instance variables for the number between cleanings and the shots since the last cleaning | Not earned if any is static, not private, or declared in the constructor |
| 3 | Constructor header EspressoMachine(int ) | Not earned with a return type or as private |
| 4 | The constructor stores its parameter in the instance variable for the number between cleanings | Not earned for assigning to a local variable |
| 5 | Method header public int brew(int ) | Not earned without public or with the wrong return or parameter type |
| 6 (algorithm) | Adds the shots and starts the count over at each cleaning, including several in one call and a count that lands exactly on the limit | Not earned if the instance variable is never updated |
| 7 | Returns a computed number of shots from brew | Earned even if the number is wrong; not earned for printing it |
Here is the class with the table's calls as a program. Press Run, then change the number between cleanings or the shots brewed, or make
shotsSinceCleaning static and watch the last line change from 5 to 6.public class Main
{
public static void main(String[] args)
{
EspressoMachine cafe = new EspressoMachine(10);
System.out.println("cafe.brew(4) returns " + cafe.brew(4));
System.out.println("cafe.brew(5) returns " + cafe.brew(5));
System.out.println("cafe.brew(1) returns " + cafe.brew(1));
System.out.println("cafe.brew(23) returns " + cafe.brew(23));
EspressoMachine kiosk = new EspressoMachine(3);
System.out.println("kiosk.brew(2) returns " + kiosk.brew(2));
System.out.println("cafe.brew(2) returns " + cafe.brew(2));
}
}
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.
Released exam index
Every released question that asks for a whole class, 2010 to 2026, except the four that extended a class of the GridWorld case study (2011 Q2, 2012 Q2, 2013 Q3, and 2014 Q2), which the course no longer includes. The ones marked "implements" or "extends" also used a feature the course no longer covers; the rest of each class is ordinary class design.
| Exam | Class | Key features |
|---|---|---|
| 2010 Q2 | APLine | Constructor with three int coefficients; slope as a double without integer division; a test for a point on the line |
| 2014 Q4 | Trio (implements) | Three objects of provided classes; a name joined from their names; a price from the two highest of three prices |
| 2015 Q2 | HiddenWord | Stores a word; a hint String built letter by letter from a guess |
| 2015 Q4(b) | Range (implements) | Minimum and maximum from the constructor; an inclusive contains test |
| 2016 Q1(a) | RandomStringChooser | Keeps a copy of an array; returns a random string not yet chosen, then "NONE" |
| 2017 Q2 | MultPractice (implements) | Two numbers from the constructor; a problem String with a literal word between them; the next problem raises the second number |
| 2018 Q3 | CodeWordChecker (implements) | Two constructors, one with default lengths; a length within an inclusive range and a String it must not contain |
| 2019 Q2 | StepTracker | Threshold from the constructor; counts active days; average as a double, 0.0 with no data |
| 2021 Q2 | CombinedTable | Two objects of a provided class; seats minus 2; an average view that drops by 10 when the heights differ, read live |
| 2022 Q2 | Textbook (extends) | An edition beside a title and a price; a String of the three joined by hyphens; a same-class method comparing titles and editions |
| 2023 Q2 | Sign | A message and a line width; the number of lines; the message cut into lines joined by semicolons, null for an empty message |
| 2024 Q2 | Scoreboard | Two team names; a play adds points or passes the turn; a score String with hyphens and the active team |
| 2025 Q2 | SignedText | First and last name; a signature with an initial and a dash; a signature added, kept, or relocated to the end of a String |
| 2026 Q2 | Bottle | Capacity from the constructor, full at the start; one method that removes an amount, refills below 25%, and returns the amount |