ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
class Outer {
    private int secret = 42;
    class Inner {
        int reveal() { return secret; }
    }
}
public class Main {
    public static void main(String[] args) {
        Outer o = new Outer();
        Outer.Inner i = o.new Inner();
        System.out.print(i.reveal());
    }
}
  1. A. 42
  2. B. 0
  3. C. Compilation error: Inner cannot access Outer's private field
  4. D. Compilation error: Inner must be static to be instantiated this way

Correct answer: A. 42

A non-static inner class has an implicit reference to its enclosing instance and may freely access that instance's private members, including secret — this is a special compiler-granted exception to normal private access rules. The syntax `o.new Inner()` correctly creates an Inner tied to o.

More OOP with C++ and Java questions

Exams that ask this topic