Page 1 of 1

About Question enthuware.ocpjp.v17.2.983 :

Posted: Tue Nov 05, 2024 11:14 am
by rlobato
Hi,

How come the explicit cast is not mandatory for

Code: Select all

 Object o = b; Runnable r = (Runnable) b;
but for

Code: Select all

Object o = b; Observer o2 = o;
it is?

b is declared of a type that indirectly implements Runnable, but isn't it declared of a type that directly implements Observer?

What do I miss?

Cheers,

Rafael

Re: About Question enthuware.ocpjp.v17.2.983 :

Posted: Tue Nov 05, 2024 10:01 pm
by admin
> Object o = b; Runnable r = (Runnable) b;

What is the declared type of the variable b? B. B extend A and A implements Runnable. Therefore, B is a Runnable. Thus the compiler already knows that b will always point to a Runnable object. So, it doesn't need any cast to allow b to be assigned to r.

>Object o = b; Observer o2 = o;
What is the declared type of o? Object. Object is not an Observer. The compile is not certain that o will always point to an Observable object. But if the developer thinks that o will point to an Observable object at runtime, the developer needs to tell the compiler to accept this assignment as correct by applying the cast.

There are several intricacies and details that are not possible to explain in a forum post. So I suggest you go through a good book that explains this concept well before attempting questions. We recommend Hanumant Deshmukh's OCA Java 8 Fundamentals: https://amzn.to/2Up2ZUk