Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard

Question 9

Question ID: UKOCP29193


Consider below codes of 3 java files:





What will be the result of compiling and executing Test class?

  • A An exception is thrown at runtime
  • B It executes successfully and prints M on to the console
  • C It executes successfully and prints N on to the console
  • D Compilation error
Reveal correct answer

Correct answer: A

Explanation

UKOCP29193:

Class M and M are declared public and inside same package com.udayankhattry.ocp. Method printName() of class M has correctly been overridden by N.

printName() method is public so no issues in accessing it anywhere.


Let's check the code inside main method.

M obj1 = new M(); => obj1 refers to an instance of class M.

N obj2 = (N)obj1; => obj1 is of type M and it is assigned to obj2 (N type), hence explicit casting is necessary. obj1 refers to an instance of class M, so at runtime obj2 will also refer to an instance of class M. sub type can't refer to an instance of super type so at runtime N obj2 = (N)obj1; will throw ClassCastException.

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.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need