Sunday 17 March 2013

SCJP - 20 - Given Example


What is the result?
A. 6
B. 7
C. 8
D. 9
E. Compilation fails.
F. An exception is thrown.

Answer:

D is correct. Minor’s constructor makes an explicit call to Uber’s 1-arg constructor,
which makes an explicit (this) call to Uber’s no-arg constructor, which increments y,
then returns to the 1-arg constructor, which multiples y * 2, and then returns to Minor’s
constructor, which adds 3 to y.

A, B, C, E, and F are incorrect based on the preceding.
(Objective 1.6)
==
class Uber {
static int y = 2;
Uber(int x) { this(); y = y * 2; }
Uber() { y++; }
}
class Minor extends Uber {
Minor() { super(y); y = y + 3; }
public static void main(String [] args) {
new Minor();
System.out.println(y);
} }


No comments:

Post a Comment