Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Easy
Question 12
Given code:
- package com.udayan.ocp;
- enum TrafficLight {
- RED, YELLOW, GREEN;
- }
- public class Test {
- public static void main(String[] args) {
- TrafficLight tl1 = TrafficLight.GREEN;
- TrafficLight tl2 = tl1.clone(); //Line 10
- System.out.println(tl2); //Line 11
- }
- }
What is the result?
- A Compilation error at Line 10
- B Line 11 throws CloneNotSupportedException at runtime
- C GREEN
Reveal correct answer
Correct answer: A
Explanation
Every enum extends from java.lang.Enum class and it contains following definition of clone method:
- protected final Object clone() throws CloneNotSupportedException {
- throw new CloneNotSupportedException();
- }
Every enum constant (RED, YELLOW, GREEN) is an instance of TrafficLight enum and as clone method is protected in Enum class so it cannot be accessed in com.udayan.ocp package using reference variable.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
