Java OCA OCP Practice Question 446

Question

Consider the following classes:

class A implements Runnable{  ...} 
class B extends A implements Observer  {  ...} 

Assume that Observer has no relation to Runnable.

and the declarations :

A a = new A () ; 
B b = new B (); 

Which of the following Java code fragments will compile and execute without throwing exceptions?

Select 2 options

  • A. Object o = a; Runnable r = o;
  • B. Object o = a; Runnable r = (Runnable) o;
  • C. Object o = a; Observer ob = (Observer) o ;
  • D. Object o = b; Observer o2 = o;
  • E. Object o = b; Runnable r = (Runnable) b;


Correct Options are  : B E

Note

Although o refers to an object which is Runnable but the compiler doesn't know about it.

You have to do: Runnable r = (Runnable) o;

You can assign a subclass object reference to superclass reference without a cast.

To assign a super class object reference to a subclass or interface reference you need an explicit cast as in option 2.




PreviousNext

Related