ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
class Outer {
    int v = 1;
    class Inner { int v = 2; int get() { return v + Outer.this.v; } }
    static class Nest { int get() { return 3; } }
}
// in main:
Outer o = new Outer();
Outer.Inner in = o.new Inner();
Outer.Nest n = new Outer.Nest();
System.out.print(in.get() + n.get());
  1. A. 6
  2. B. 5
  3. C. 33
  4. D. Compile error at o.new Inner()

Correct answer: A. 6

An inner (non-static) class needs an enclosing instance, created with o.new Inner(); its v is 2 and Outer.this.v is 1, so get() returns 3. A static nested class needs no instance and returns 3: 3 + 3 = 6.

More OOP with C++ and Java questions

Exams that ask this topic