🎙 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 5 of 10

What does this print? (code)

What does this print?

public class Main {
    String name = "outer";

    void test() {
        Runnable r1 = new Runnable() {
            String name = "anon";
            public void run() { System.out.print(this.name + " "); }
        };
        Runnable r2 = () -> System.out.println(this.name);
        r1.run();
        r2.run();
    }

    public static void main(String[] args) {
        new Main().test();
    }
}
  1. A.outer outer
  2. B.anon anon
  3. C.anon outer
  4. D.outer anon
Answer & explanation

Correct answer: anon outer

In the anonymous class, this is the anonymous object; in the lambda, this is the Main object.

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 →