Java Magazine, May/June 2018
ORACLE COM JAVAMAGAZINE MAY JUNE 2018 96 fix this Answer 3 The correct answers are option A and option B This question is essentially about things you cant do with lambda expressions Both of the first two options successfully create objects from anonymous inner classes that subclass the abstract class Stuff Although it might be more common to create anonymous classes that are constructed with zero arguments its entirely possible to use arguments in the construction process provided the parent class defines the target constructor This requirement means that its not possible to have constructor arguments for anonymous inner classes that are defined in terms of an interface because no parent constructors can exist in an interface Therefore only the zeroargument form is possible Its also not possible to define an explicit constructor in the anonymous inner class itself However the code in both option A and option B interacts properly with the available constructors of the Stuff parent class In fact both option A and option B compile correctly and execute successfully and the output x is 9 for option A and 18 for option B As a result both option A and option B are correct Option C attempts to use a lambda expression to define the implementation of the abstract method in the Stuff class However the syntax presented is entirely bogus and option C is incorrect Option D is more plausible than option C However it is only permissible to define lambda expressions to satisfy the behavioral requirement of a functional interface A functional interface is one that has exactly one abstract method and of course the class Stuff has exactly one abstract method which might make this option tempting However a functional interface is an interface and its not possible to use a lambda to create a concrete implementation of an abstract class even if it has exactly one abstract method Therefore option D is incorrect Answer 4 The correct answer is option B This question investigates the method reference syntax introduced with lambda expressions in Java 8 Method references are an alternative syntax that addresses one of four situations that occur fairly frequently in lambda expressions Four forms are available Table 1 shows how a lambda in the conventional arrow form may be translated to or from the method reference form
You must have JavaScript enabled to view digital editions.