This question includes a topic, interfaces, that is no longer part of the AP Java subset and will not be directly tested on current exams. Inheritance is still a tested topic, and this problem is a good example of working with inheritance.
Question #2 on the 2017 AP Computer Science exam was testing your ability to use an arbitrary Java interface called StudyPractice
. You were to implement this interface to create a class called MultPractice
.
The StudyPractice
interface, defined below, specifies two methods that you must implement; getProblem
and nextProblem
.
public interface StudyPractice {
/** Returns the current practice problem */
String getProblem();
/** Changes to the next practice problem */
void nextProblem();
}
Our implementation of MultPractice
must implement both of these methods.
public class MultPractic implements StudyPractice {
private int numOne;
private int numTwo;
public MultPractice(int a, int b) {
numOne = a;
numTwo = b;
}
public String getProblem() {
return numOne + " TIMES " + numTwo;
}
public void nextProblem() {
numTwo++;
}
Let’s start with the first line. We’re creating a class called MultPractice
that implements the interface StudyPractice
.
For this class we’ll need two int
instance variables. Names don’t really matter, but they do both need to be private
. That’s a College Board preference that all instance variables should be private
and they typically will take off points if you do not specify instance variable as private
.
The constructor takes two int
parameters. We know this because of the examples in the problem. There are several example calls similar to StudyPractice p1 = new MultPractice(7, 4)
. This tells us that the constructor must take two int
parameters.
Then we implement the getProblem
and nextProblem
methods. getProblem
returns a string in a specific format, starting with the first number, followed by " TIMES "
, followed by the second number. nextProblem
increments the second number so that the next time getProblem
is called it will return a different string.