Question 10
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
class Rect {
final int w, h;
Rect(int w, int h) { this.w = w; this.h = h; }
Rect(int side) { this(side, defaultHeight()); }
int defaultHeight() { return 10; }
}
public class Main {
public static void main(String[] args) {
System.out.println(new Rect(4).h);
}
}
- A h must not be final
- B The object is not constructed yet when this(...) arguments are evaluated, so an instance method cannot be called there; make defaultHeight static Correct
- C Rect cannot have two constructors
- D this(...) cannot take expressions
Correct Answer: Option B
javac: "cannot reference this before supertype constructor has been called".
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!