Question 10
Back to Exercise
What is the output of the following Java program?
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!