LearnFrenzy
Sign in Take a free test

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

Error: constructors calling each other forever Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

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

Main.java
class Loop {
    int v;
    Loop() { this(0); }
    Loop(int v) { this(); this.v = v; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Loop(5).v);
    }
}
  • A v must be final
  • B Loop() and Loop(int) call each other, so javac reports "recursive constructor invocation" Correct
  • C this cannot be used in constructors
  • D It compiles but overflows the stack
Correct Answer: Option B

One constructor must do the real work without calling back.

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