Question 1
Main declares one static nested class and one inner class, both reading private members of the enclosing class. What is the result?
public class Main {
private static int secret = 42;
private int instanceVal = 7;
static class Vault {
int peek() {
return secret;
}
}
class Room {
int peek() {
return instanceVal + secret;
}
}
public static void main(String[] args) {
Main m = new Main();
Room r = m.new Room();
System.out.println(new Vault().peek() + " " + r.peek());
}
}A. 42 7
Reads only instanceVal for the inner class and omits secret; Room returns instanceVal + secret = 7 + 42 = 49, not 7.
B. Compilation fails
Assumes private members are hidden from nested types; a nested class is a member of its enclosing class and may read its private fields, so it compiles.
C. 42 49Correct answer
Correct — the static nested Vault reads the static secret (42), and the inner Room reads both instanceVal (7) and secret (42) for 49, since nested classes may access the enclosing class's private members (JLS 17 §8.5).
D. 49 42
Swaps the two results; the static nested class prints 42 and the inner-class instance prints 49, so the order is 42 then 49.
Explanation
A nested class is a member of its enclosing class, so it may read the enclosing class's private members: Vault (static nested, no enclosing instance needed) sees the static field secret = 42, and Room (inner) sees both instanceVal = 7 and secret, giving 49. Compilation fails is the trap for thinking private members are hidden from nested types; the qualified creation expression m.new Room() is the correct — and required — way to build an inner-class instance from a static context, since an inner class has no existence without an enclosing instance.