Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 9
Question ID: UKOCP29193
Consider below codes of 3 java files:
- //M.java
- package com.udayankhattry.ocp;
- public class M {
- public void printName() {
- System.out.println("M");
- }
- }
- //N.java
- package com.udayankhattry.ocp;
- public class N extends M {
- public void printName() {
- System.out.println("N");
- }
- }
- //Test.java
- package com.udayankhattry.ocp.test;
- import com.udayankhattry.ocp.*;
- public class Test {
- public static void main(String[] args) {
- M obj1 = new M();
- N obj2 = (N)obj1;
- obj2.printName();
- }
- }
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.
