LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 10

An inner class reading its outer object's field Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    private String name;

    Main(String name) { this.name = name; }

    class Greeter {
        String greet() { return "Hello from " + name; }
    }

    public static void main(String[] args) {
        Main a = new Main("A"), b = new Main("B");
        Main.Greeter ga = a.new Greeter();
        Main.Greeter gb = b.new Greeter();
        a.name = "A2";
        System.out.println(ga.greet() + " | " + gb.greet());
    }
}
  • A Hello from A2 | Hello from B Correct
  • B Hello from A | Hello from B
  • C Hello from B | Hello from B
  • D Compilation error
Correct Answer: Option A

Each inner object keeps a reference to its own outer object, so it sees later changes to that object's fields.

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