Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 84
Question ID: UKOCP52747
Given code:
- package com.udayankhattry.ocp;
- interface Dancer {
- default void dance() {
- System.out.println("DANCER");
- }
- }
- interface TapDancer extends Dancer {
- void dance();
- }
- public class Test {
- public static void main(String[] args) {
- TapDancer td = () -> System.out.println("TAPDANCER"); //Line n1
- ((Dancer)td).dance(); //Line n2
- }
- }
What is the result?
- A TAPDANCER
- B DANCER
- C Compilation error in TapDancer interface
- D Compilation error in Test class
- E An exception is thrown at runtime
Reveal correct answer
Correct answer: A
Explanation
UKOCP52747:
Interfaces in Java can define default methods, hence no issues with Dancer interface.
Interface TapDancer is a Functional Interface, as it has one non-overriding abstract method dance(). Interfaces in java are allowed to override default method with abstract method. Interface TapDancer compiles successfully.
As TapDancer is a Functional Interface, hence it can be a target type of lambda expression. Line n1 compiles successfully.
Dancer is a supertype of TapDancer, hence reference variable can be easily typecasted to Dancer. And dance() method is available in Dancer interface, so no issues with Line n2 as well, it compiles successfully. But at runtime, method of lambda expression will be invoked.
Given code executes successfully and prints TAPDANCER on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
