Java OCA OCP Practice Question 424

Question

Consider the following classes :

interface I{ //  www . j  ava 2 s .  c o  m
} 
class A implements I{ 
} 

class B extends A  { 
} 

class C extends B{ 
} 

And the following declarations:

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

Identify options that will compile and run without error.

Select 1 option

  • A. a = (B)(I)b;
  • B. b = (B)(I) a;
  • C. a = (I) b;
  • D. I i = (C) a;


Correct Option is  : A

Note

A. is a correct answer.

class B does implement I because it extends A, which implements I.

A reference of type I can be cast to any class at compile time.

Since B is-a A, it can be assigned to a.

B. is wrong.

This will fail at run time because a does not point to an object of class B.

C. is wrong.An I is not an A. Therefore, it will not compile.

D. is wrong.

It will compile because a C is-a A, which is-a I.

A reference of class A can point to an object of class C.

But it will fail at runtime because a does not point to an object of class C.




PreviousNext

Related