Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 94
Question ID: UKOCP75425
Given code:
- package com.udayankhattry.ocp;
- abstract class Greetings {
- abstract void greet();
- }
- public class Test {
- public static void main(String[] args) {
- var obj = new Greetings() {
- @Override public void greet() {
- System.out.println("BELIEVE IN YOURSELF");
- }
- };
- obj.greet();
- }
- }
What will be the result of compiling and executing Test class?
- A Compilation error
- B NullPointerException
- C BELIEVE IN YOURSELF
- D Nothing is printed on to the console
Reveal correct answer
Correct answer: C
Explanation
UKOCP75425:
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.
obj refers to an anonymous inner class instance extending from Greetings class and the anonymous inner class code correctly overrides greet() method.
Code executes and prints BELIEVE IN YOURSELF on to the console.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
