Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 60
Question ID: UKOCP36738
Consider below codes of 4 java files:
- //A.java
- package com.udayankhattry.ocp;
- public class A {
- public void print() {
- System.out.println("A");
- }
- }
- //B.java
- package com.udayankhattry.ocp;
- public class B extends A {
- public void print() {
- System.out.println("B");
- }
- }
- //C.java
- package com.udayankhattry.ocp;
- public class C extends A {
- public void print() {
- System.out.println("C");
- }
- }
- //Test.java
- package com.udayankhattry.ocp.test;
- import com.udayankhattry.ocp.*;
- public class Test {
- public static void main(String[] args) {
- A obj1 = new C();
- A obj2 = new B();
- C obj3 = (C)obj1;
- C obj4 = (C)obj2;
- obj3.print();
- }
- }
What will be the result of compiling and executing Test class?
- A It executes successfully and prints A on to the console
- B It executes successfully and prints B on to the console
- C It executes successfully and prints C on to the console
- D Compilation error
- E An exception is thrown at runtime
Reveal correct answer
Correct answer: E
Explanation
UKOCP36738:
Class A, B and C are declared public and are inside same package 'com.udayankhattry.ocp'. Method print() of class A has correctly been overridden by B and C.
print() method is public so no issues in accessing it anywhere.
Let's check the code inside main method.
A obj1 = new C(); => obj1 refers to an instance of C class, it is polymorphism.
A obj2 = new B(); => obj2 refers to an instance of B class, it is polymorphism.
C obj3 = (C)obj1; => obj1 actually refers to an instance of C class, so at runtime obj3 (C type) will refer to an instance of C class. As obj1 is of A type so explicit typecasting is necessary.
C obj4 = (C)obj2; => obj2 actually refers to an instance of B class, so at runtime obj4 (C type) will refer to an instance of B class. B and C are siblings and can't refer to each other, so this statement will throw ClassCastException at runtime.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
