ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class Outer {
    static int x = 100;
    static class Nested {
        int x = 200;
        void show() { System.out.println(x + " " + Outer.x); }
    }
}
public class Main {
    public static void main(String[] args) {
        new Outer.Nested().show();
    }
}
  1. A. 200 100
  2. B. 100 200
  3. C. 200 200
  4. D. Compile-time error: Nested cannot access Outer.x without an Outer instance

Correct answer: A. 200 100

Nested is a static nested class, so it has no implicit reference to an enclosing Outer instance, but it can still freely access Outer's static members by qualifying them, Outer.x. show() prints its own instance field x (200) and then the qualified Outer.x (100).

More OOP with C++ and Java questions

Exams that ask this topic