ProgrammingHardTCS NQT · Infosys pattern
Does this compile?
Does this compile?
class Outer {
private int x = 5;
class Inner {
void show() { System.out.println(x); }
}
}- A. No: x is private, so Inner cannot read it even though it is a nested class
- B. Yes: a non-static inner class has access to all members of its enclosing class, including private ones
- C. Yes, but only if x is declared protected instead
- D. No: Inner must explicitly import Outer's private members
Correct answer: B. Yes: a non-static inner class has access to all members of its enclosing class, including private ones
An inner (non-static nested) class is tightly coupled to its enclosing instance and the compiler generates synthetic accessors as needed, so it can freely read and write private members of the enclosing class. This is a compiler trick, not a relaxation of the access rule itself.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual void f() { cout << "Base"; } }; struct Derived : Base { void f() { cout << "Derived"; } }; int…
- What is printed? java class Picker { static void f(int a, int b) { System.out.print("fixed"); } static void f(int... a) {…
- What happens when this is compiled? cpp struct Base final { virtual void f() { cout << "Base"; } }; struct Derived : Base { };
- What is printed? cpp struct Base {}; struct Derived : Base {}; void f(Base b) { cout << "Base"; } void f(Derived d) { cout << "Derived"; }…
- What is printed? cpp struct Shape { virtual double area() const = 0; virtual ~Shape() = default; }; struct Square : Shape { double s…
- What is printed? java abstract class Shape { abstract double area(); public String toString() { return "Shape(area=" + area() + ")"; } }…