Java Magazine, July/August 2018
ORACLE COM JAVAMAGAZINE JULY AUGUST 2018 84 fix this cares what its called it just does exactly what it says on the can The syntax of an anonymous class can create an object that is derived from a class abstract or concrete or that implements an interface Because of this trait both option A and option B are correct Regardless of whether a class is being extended or an interface is being implemented if the parent is called BaseType the syntax looks like this BaseType anon new BaseType implementation specific code here usually overriding method s This syntax unlike the more general implements clause that may be used when declaring a regular class permits only a single base type to be specified Consequently option C is incorrect If the anonymous class is to serve any useful purpose some code must be provided in the body If BaseType is an interface it presumably declares an abstract method or methods that must be implemented If BaseType is a class you must modify some behavior otherwise you might as well have simply instantiated BaseType directly In Java a constructor is defined using the name of the class that it initializes If no such name exists then clearly no explicit constructor is possible Despite this however the anonymous form allows parameters to the construction for example new BaseType 12 provided that those arguments match an existing constructor in BaseType and of course BaseType must be a class because interfaces do not have constructors We mentioned earlier that the anonymous class form can build an object based on a class either concrete or abstract or an interface A lambda expression however can be created only to implement an interface Therefore there are things that anonymous classes can do that lambdas cannot do which tells you that option D is incorrect In fact lambda expressions have another restriction not applicable to anonymous classes an anonymous class can override or implement many methods but a lambda expression pro
You must have JavaScript enabled to view digital editions.