1Z0-819 · Question #47
Given 1. public class Test { 2. private static class Greet { 3. private void print() { 4. System.out.println("Hello World"); 5. } 6. } 7. public static void main(String[] args) { 8. Test.Greet g =…
The correct answer is C. Hello World. Option C is correct because Java grants the enclosing class full access to all private members of its nested classes, including both the class itself and its methods. Since main lives inside Test, it can legally reference the private Greet class and call its private print()…
Question
- public class Test {
- private static class Greet {
- private void print() {
- System.out.println("Hello World");
- }
- }
- public static void main(String[] args) {
- Test.Greet g = new Greet();
- g.print();
- }
- }
Options
- AThe compilation fails at line 9.
- BThe compilation fails at line 2.
- CHello World
- DThe compilation fails at line 8.
How the community answered
(18 responses)- A6% (1)
- C83% (15)
- D11% (2)
Explanation
Option C is correct because Java grants the enclosing class full access to all private members of its nested classes, including both the class itself and its methods. Since main lives inside Test, it can legally reference the private Greet class and call its private print() method without any access violation, so the code compiles and prints "Hello World."
Option B is wrong because private static nested classes are perfectly valid Java - the private modifier simply restricts visibility to the enclosing class, which is exactly how it is used here. Option D is wrong because Test.Greet g = new Greet() is valid syntax inside the enclosing class; Greet is in scope and can be instantiated directly. Option A is wrong for the same reason as the premise of D - g.print() is a legal call because the outer class bypasses private access restrictions on its own nested types.
Memory tip: Think of an outer class and its nested classes as members of the same family - Java lets them see each other's private details, so access modifiers between them are transparent in both directions.
Topics
Community Discussion
No community discussion yet for this question.