Return to site

☕🎓JAVA CERTIFICATION QUESTION: anonymous classes

· java,ocp

Imagine that you are doing an audit of a third-party desktop Java application

that interacts with users’ input and has the following code:

Based on the provided code fragment, which statement is true about the Handler type? Choose one.

* It must be an interface.

* It must be an abstract class.

* It can be a concrete class.

* It can be either a class or an interface.

* It can be a class, an interface, or an enum.

* It can be a class, an interface, an enum, or a record.

#java #certificationquestion #ocp

Answer: It can be a concrete class.

In general, an anonymous class can extend a class, either a concrete or an abstract class, or it can implement an interface.

The declaration/instantiation of an anonymous class includes a parameter list.

If the parent type is a class (either abstract or concrete), that parameter list is passed to the parent class’s constructor.

If the parent type is an interface, the parameter list must be empty.

So, here, that anonymous class is not constrained to either implement an interface or extend an abstract class.

Plus, in general, an anonymous class can be derived from a concrete or abstract class or from an interface.

Then, Enum types place strict limits on their subtypes : any such subtype is implicitly final, so it cannot possibly be a subtype of an enum.

Also, any method declared in an interface will default to being public if no explicit modifier is given,

and most methods in an interface can be declared explicitly public.

Static and concrete instance methods can also be declared as private.

However, no interface method can have any intermediate accessibility—that is, no interface method can have package level, or protected, accessibility.

Here if you override the interface method, it must be public.

However, the method handle(Event e) in the anonymous class has package accessibility.

So based on previous statements, it must not be an interface or absatract class, it is neither an enum, neither an interface.

In the end only the statement "It can be a concrete class" is correct.