🎙 Free live masterclass · Sun, 29 Nov, 7:00 pm IST · Java Full Stack roadmap Register free →
Skills101
← Quiz: Nested and Anonymous Classes: all 10 questions

Quiz: Nested and Anonymous Classes · Question 3 of 10

What does this print? (code)

What does this print?

class Outer {
    int x = 10;
    class Inner {
        int x = 20;
        int sum() { return x + Outer.this.x; }
    }
}

public class Main {
    public static void main(String[] args) {
        Outer o = new Outer();
        Outer.Inner i = o.new Inner();
        o.x = 5;
        System.out.println(i.sum());
    }
}
  1. A.30
  2. B.40
  3. C.10
  4. D.25
Answer & explanation

Correct answer: 25

x is the inner field (20); Outer.this.x reads the outer object's current value, 5.

Can you get the rest right without peeking?

Take the timed Quiz: Nested and Anonymous Classes quiz free. Pass it to earn XP and count towards your certificate.

Start the quiz →