In Java, which statement about a static nested class is correct?
-
AYou must have a reference to an instance of the enclosing class in order to instantiate it.
-
BIt does not have access to nonstatic members of the enclosing class.
-
CIts variables and methods must be static.
-
DIt must extend the enclosing class.
-
EIt can implicitly access all members of the enclosing class, static or not.
Answer
Correct Answer: It does not have access to nonstatic members of the enclosing class.
Explanation
Introduction / Context:Static nested classes in Java are often confused with inner classes. The key differences revolve around access to members of the enclosing class and whether an enclosing instance is required.
Given Data / Assumptions:
- The nested type in question is declared
staticinside an outer class. - We must select a true statement describing capabilities and constraints.
Concept / Approach:A static nested class is associated with its outer class's type, not with any specific outer instance. It can access outer class static members directly but cannot access instance (nonstatic) members without an explicit outer object reference. Unlike inner (non-static) classes, no implicit reference to the enclosing instance is captured.
Step-by-Step Solution:
Recognize thatstatic removes the implicit outer-instance binding.Conclude it cannot access nonstatic members unless you pass an outer instance explicitly and use it like any other object.Therefore, the correct choice is that it does not have access to nonstatic members of the enclosing class.Verification / Alternative check:Try referencing an instance field from a static nested class without an outer reference; the compiler will report an error. Accessing a static outer field compiles.
Why Other Options Are Wrong:Option A applies to nonstatic inner classes, not static nested classes. Option C is incorrect: a static nested class can contain instance members. Option D is false: no inheritance requirement. Option E is the opposite of the rule; only static members are directly accessible.
Common Pitfalls:Assuming all nested classes behave like inner classes; forgetting the difference in member access and instantiation.
Final Answer:It does not have access to nonstatic members of the enclosing class.