LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Find the Error · Question 10

Error: using an instance method in a this(...) argument Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links