ProgrammingHardAccenture · Cognizant pattern
What is printed?
What is printed?
class Outer {
private int secret = 42;
class Inner {
int reveal() { return secret; }
}
}
public class Main {
public static void main(String[] args) {
Outer o = new Outer();
Outer.Inner i = o.new Inner();
System.out.print(i.reveal());
}
}- A. 42
- B. 0
- C. Compilation error: Inner cannot access Outer's private field
- D. Compilation error: Inner must be static to be instantiated this way
Correct answer: A. 42
A non-static inner class has an implicit reference to its enclosing instance and may freely access that instance's private members, including secret — this is a special compiler-granted exception to normal private access rules. The syntax `o.new Inner()` correctly creates an Inner tied to o.
More OOP with C++ and Java questions
- Which statement about overload resolution with varargs is correct? java class A { void f(int a, int b) { System.out.print("fixed"); } void…
- Which statement is correct? java interface Shape { double area(); } abstract class AbstractShape implements Shape { public abstract double…
- What is printed? java class Stack<T> { private List<T> items = new ArrayList<>(); void push(T item) { items.add(item); } T pop() { return…
- Which statement is correct? java class Event { protected void log() { System.out.print("Event.log"); } } class ClickEvent extends Event {…
- What is printed? java class Base { public Base() { System.out.print("Base "); } public Base(Base other) { System.out.print("BaseCopy "); }…
- What is printed? cpp struct Base { virtual void run() { step1(); step2(); } virtual void step1() { cout << "B1 "; } virtual void step2() {…