LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Predict the Output · Question 1

A constructor counting objects Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

What is the output of the following Java program?

Main.java
class Visitor {
    static int count = 0;
    final int id;
    Visitor() { count++; id = count * 100; }
}

public class Main {
    public static void main(String[] args) {
        Visitor a = new Visitor();
        Visitor b = new Visitor();
        new Visitor();
        System.out.println(a.id + " " + b.id + " " + Visitor.count);
    }
}
  • A 100 200 3 Correct
  • B 300 300 3
  • C 100 200 2
  • D 0 0 3
Correct Answer: Option A

The constructor runs once for each new, even when the object is not stored.

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