ProgrammingHardProduct-company placement · Java

Which line fails to compile?

Which line fails to compile?
class Outer {
    int x = 1;
    class In { int get() { return x; } }
    static class SN { int get() { return 2; } }
}
// in main (a static method of another class):
Outer.SN a = new Outer.SN();        // L1
Outer.In b = new Outer.In();        // L2
Outer.In c = new Outer().new In();  // L3
  1. A. L1 only
  2. B. L1 and L2
  3. C. L2 only
  4. D. None of them

Correct answer: C. L2 only

A static nested class needs no outer object (L1). An inner (non-static) class instance is tied to an Outer instance, so it must be created as outerRef.new In() (L3); L2 has no enclosing instance.

More OOP with C++ and Java questions

Exams that ask this topic