Given: class Bird{ public void fly (){System.out.print("Can fly"); } } class Penguin extends Bird{ public void fly (){System.out.print("Cannot fly"); } } and the code fragment: class Birdie { public static void main (String [ ] args){ fly( ( ) -> new Bird ( )); fly (Penguin : : new); } /* line n1 */ } Which code fragment, when inserted at line n1, enables the Birdie class to compile?
Click on the arrows to vote for the correct answer
A. B. C. D.C.
The code snippet defines two classes: Bird
and Penguin
, where Penguin
is a subclass of Bird
. Both classes have a method fly()
that prints a message indicating whether the bird can fly or not.
The Birdie
class has a main
method, which calls the fly
method twice, each time with a different argument.
The problem with the given code is that there is no fly
method defined in the Birdie
class or in any of its superclasses or imported classes. Therefore, the code will not compile unless a valid fly
method is added.
Option A:
javascriptstatic void fly(Consumer<Bird> bird) { bird::fly(); }
This option defines a static fly
method that takes a Consumer<Bird>
argument. A Consumer
is a functional interface that takes an argument and returns nothing. In this case, the Consumer
takes a Bird
argument and calls its fly
method. This option is valid because both Bird
and Penguin
are Bird
instances, so they can be passed as arguments to the fly
method.
Option B:
javascriptstatic void fly(Consumer<? extends Bird> bird) { bird.accept().fly(); }
This option defines a static fly
method that takes a Consumer<? extends Bird>
argument. This means that the Consumer
can take any object that extends Bird
. In the method body, the accept
method of the Consumer
is called, which returns a Bird
object, and then the fly
method of the returned object is called. This option is valid because both Bird
and Penguin
are Bird
instances, so they can be passed as arguments to the fly
method.
Option C:
scssstatic void fly(Supplier<Bird> bird) { bird.get().fly(); }
This option defines a static fly
method that takes a Supplier<Bird>
argument. A Supplier
is a functional interface that takes no arguments and returns an object of the specified type. In this case, the Supplier
returns a Bird
object, and then the fly
method of the returned object is called. This option is valid because both Bird
and Penguin
are Bird
instances, so they can be returned by the Supplier
.
Option D:
javascriptstatic void fly(Supplier<? extends Bird> bird) { bird.get().fly(); }
This option is similar to option C, but the Supplier
can take any object that extends Bird
. This option is also valid because both Bird
and Penguin
are Bird
instances, so they can be returned by the Supplier
.
Therefore, options A, B, C, and D are all valid solutions that would allow the Birdie
class to compile. The correct option will depend on the specific requirements of the program.