ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
class T {
    String name = "outer";
    void run() {
        Runnable a = () -> System.out.print(this.name + " ");
        Runnable b = new Runnable() {
            String name = "anon";
            public void run() { System.out.print(this.name); }
        };
        a.run(); b.run();
    }
}
// in main:
new T().run();
  1. A. anon anon
  2. B. outer outer
  3. C. outer anon
  4. D. Compile-time error: this cannot be used in a lambda

Correct answer: C. outer anon

A lambda does not introduce a new scope for this: it refers to the enclosing T. An anonymous class is a real class, so its this is the anonymous object with its own name field.

More OOP with C++ and Java questions

Exams that ask this topic