Java — Truths about anonymous inner classes (capabilities and limitations)
-
AIt can extend exactly one class and implement exactly one interface.
-
BIt can extend exactly one class and can implement multiple interfaces.
-
CIt can extend exactly one class or implement exactly one interface.
-
DIt can implement multiple interfaces regardless of whether it also extends a class.
Answer
Correct Answer: It can extend exactly one class or implement exactly one interface.
Explanation
Introduction / Context:This conceptual question checks the constraints on Java anonymous inner classes: how many super types they can specify and whether they can both extend and implement simultaneously.
Given Data / Assumptions:
- Anonymous class syntax: new SuperType(...) { ... }.
- SuperType may be a class or an interface.
Concept / Approach:An anonymous class must either extend one concrete/abstract class or implement one interface, not both, and not multiple interfaces at once. There is only one type name in the creation expression.
Step-by-Step Explanation:
If SuperType is a class, the anonymous class implicitly extends it; it cannot list interfaces there.If SuperType is an interface, the anonymous class implicitly implements that interface; it cannot list additional interfaces or a separate superclass.Verification / Alternative check:Try writing new A() implements B { } or new A() extends B { } — such constructs are not legal in Java for anonymous classes.
Why Other Options Are Wrong:
- Options A, B, and D incorrectly allow both extending and implementing or multiple interfaces.
Common Pitfalls:Confusing anonymous inner classes with named classes where you could implement multiple interfaces.
Final Answer:It can extend exactly one class or implement exactly one interface.