LearnFrenzy
Sign in Take a free test

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

Passing this to another object Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayList;
import java.util.List;

class Club {
    final List<Member> members = new ArrayList<>();
    void register(Member m) { members.add(m); }
}

class Member {
    final String name;
    Member(String name, Club club) {
        this.name = name;
        club.register(this);          // the new object registers itself
    }
}

public class Main {
    public static void main(String[] args) {
        Club c = new Club();
        Member a = new Member("Asha", c);
        new Member("Ravi", c);
        System.out.println(c.members.size() + " " + (c.members.get(0) == a) + " " + c.members.get(1).name);
    }
}
  • A 2 true Ravi Correct
  • B 1 true Asha
  • C 2 false Ravi
  • D 0 false null
Correct Answer: Option A

this is passed to register, so the club stores references to the new members. (Letting this escape from a constructor needs care in multithreaded code.)

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