ProgrammingHardTCS NQT · Infosys pattern

Does this compile?

Does this compile?
class Outer {
    private int x = 5;
    class Inner {
        void show() { System.out.println(x); }
    }
}
  1. A. No: x is private, so Inner cannot read it even though it is a nested class
  2. B. Yes: a non-static inner class has access to all members of its enclosing class, including private ones
  3. C. Yes, but only if x is declared protected instead
  4. D. No: Inner must explicitly import Outer's private members

Correct answer: B. Yes: a non-static inner class has access to all members of its enclosing class, including private ones

An inner (non-static nested) class is tightly coupled to its enclosing instance and the compiler generates synthetic accessors as needed, so it can freely read and write private members of the enclosing class. This is a compiler trick, not a relaxation of the access rule itself.

More OOP with C++ and Java questions

Exams that ask this topic