Final Exam Information Sample Problem 3
Consider the following class:
class Pair {
Pair first;
Pair second;
Pair(Pair f, Pair s) { first = f; second = s; }
public static void main(String[] args) {
Pair p = new Pair(null, null);
Pair q = new Pair(null, null);
Pair r = new Pair(p, q);
System.out.println(r.function());
}
int function() {
int left, right;
if (first == null) { left = 0; }
else { left = first.function(); }
if (second == null) { right = 0; }
else { right = second.function(); }
return 1 + left + right;
}
}
The first three lines of method main create three objects
and using intermediate variables p and q eventually
assign a Pair object to r. Draw a diagram that describes
the structure to which r points after the third assignment.
What will be the output of this program when you compile it and run it?
Briefly justify your answer below.
What is a good name for the instance method function? What does
it compute? What would the result be if we were to invoke p.function()
instead of r.function() in the last line of main?
Suppose we add a new line
at the beginning of methodPair b = new Pair();
main. Does the program still
compile? Why?