Java OCA OCP Practice Question 338

Question

Given the following class definitions :

interface MyInterface{}; 
class A  {}; 
class B extends A implements MyInterface{}; 
class C implements MyInterface{}; 

and the following object instantiations:

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

Which of the following assignments are legal at compile time?

Select 1 option

A. b = c; 
B. c = b; 
C. MyInterface i = c; 
D. c =  (C) b; 
E. b = a; 


Correct Option is  : C

Note

A. is wrong

There is no relation between b and c.

B. is wrong

There is no relation between b and c.

C. is correct

Because C implements I.

D. is wrong

Compiler can see that in no case can an object referred to by b can be of class c.

So it is a compile time error.

E. is wrong

It will fail at compile time because a is of class A and can potentially refer to an object of class A, which cannot be assigned to b, which is a variable of class B.

To make it compile, you have to put an explicit cast.




PreviousNext

Related