Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 87
Question ID: UKOCP42123
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.io.IOException;
- class Super {
- Super() throws RuntimeException {
- System.out.print("CARPE ");
- }
- }
- class Sub extends Super {
- Sub() throws IOException {
- System.out.print("DIEM ");
- }
- }
- public class Test {
- public static void main(String[] args) throws Exception {
- new Sub();
- }
- }
What will be the result of compiling and executing Test class?
- A Compilation error in both Super and Sub classes
- B Compilation error only in Super class
- C Compilation error only in Sub class
- D Test class executes successfully and prints CARPE DIEM on to the console
- E Test class executes successfully and prints DIEM CARPE on to the console
Reveal correct answer
Correct answer: D
Explanation
UKOCP42123:
It is legal for the constructors to have throws clause.
Constructors are not inherited by the Sub class so there is no method overriding rules related to the constructors but as one constructor invokes other constructors implicitly or explicitly by using this(...) or super(...), hence exception handling becomes interesting.
Java compiler adds super(); as the first statement inside Sub class's constructor:
- Sub() throws IOException {
- super(); //added by the compiler
- System.out.println("DIEM");
- }
super(); invokes the constructor of Super class (which declares to throw RuntimeException), as RuntimeException is unchecked exception, therefore no handling is necessary in the constructor of Sub class.
Sub class's constructor declares to throw IOException but main(String []) method handles it.
There is no compilation error and output is: CARPE DIEM
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
