Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 31
Question ID: UKOCP20750
Below is the code of Test.java file:
- package com.udayankhattry.ocp;
- interface Flyable {
- void fly();
- }
- public class Test {
- public static void main(String[] args) {
- /*INSERT*/
- }
- }
Which of the following options can replace /*INSERT*/ such that there are no compilation errors?
Select 2 options.
-
A
Flyable flyable = new Flyable(); -
B
Flyable flyable = new Flyable(){}; -
C
- Flyable flyable = new Flyable() {
- public void fly() {
- System.out.println("Flying high");
- }
- }
-
D
- Flyable flyable = new Flyable() {
- public void fly() {
- System.out.println("Flying high");
- }
- };
-
E
- var flyable = new Flyable() {
- @Override
- public void fly() {
- System.out.println("Flying high");
- }
- public void stop() {
- System.out.println("Stopping");
- }
- };
- flyable.fly();
- flyable.stop();
Reveal correct answers
Correct answers: D, E
Explanation
UKOCP20750:
Let's check all the options one by one:
Flyable flyable = new Flyable();
✗ Can't instantiate an interface.
Flyable flyable = new Flyable(){};
✗ fly() method has not been implemented.
- Flyable flyable = new Flyable() {
- public void fly() {
- System.out.println("Flying high");
- }
- }
✗ semicolon is missing at the end
- Flyable flyable = new Flyable() {
- public void fly() {
- System.out.println("Flying high");
- }
- };
✓ Correct syntax, fly() method has been implemented successfully.
- var flyable = new Flyable() {
- @Override
- public void fly() {
- System.out.println("Flying high");
- }
- public void stop() {
- System.out.println("Stopping");
- }
- };
- flyable.fly();
- flyable.stop();
✓ Local variable Type inference was added in JDK 10.
Reserved type name var is allowed in JDK 10 onwards for local variable declarations with initializers, enhanced for-loop indexes, and index variables declared in traditional for loops. For example,
var x = "Java"; //x infers to String
var m = 10; //m infers to int
The identifier var is not a keyword, hence var can still be used as variable name, method name or package name but it cannot be used as a class or interface name.
Variable 'flyable' infers to anonymous inner class implementing Flyable interface. The anonymous inner class correctly overrides fly() method and provides a new stop() method. Both these methods can be invoked on reference variable 'flyable' as it is of anonymous inner class type.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
