About Question enthuware.ocpjp.v17.2.983 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
rlobato
Posts: 10
Joined: Fri Jun 28, 2024 3:08 am
Contact:

About Question enthuware.ocpjp.v17.2.983 :

Post 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

admin
Site Admin
Posts: 10384
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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

Post Reply

Who is online

Users browsing this forum: No registered users and 13 guests