About Question com.enthuware.ets.scjp.v6.2.493 :

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

Moderator: admin

Post Reply
ETS User

About Question com.enthuware.ets.scjp.v6.2.493 :

Post by ETS User »

Hi,

Really between interface references all is possible and compilable, not?

Is different for example than when we work with assignations between objects, in this case the inheritance tree is considered.

Runnable r2 = (Runnable) new Object();
MyInterface my1 = (MyInterface) r2;

The compiler does not check anything?

Really r2 is not a reference a object that implements MyInterface...

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

Re: About Question com.enthuware.ets.scjp.v6.2.493 :

Post by admin »

Not sure if I understand your question but the given code is valid. The compiler can only check whatever can be logical deduced from the code. In this case, when the compiler see the line "MyInterface my1 = (MyInterface) r2;", it thinks it is possible that r2 points to an object that implements MyInterface because the reference type of r2 is an interface and not a class and so it accepts the statement. Of course, it will fail at run time.

This is because at compile time only the declared information about the variables is available. The actual objects are created at run time and their exact types can be known only at run time because of polymorphism.

HTH,
Paul.
If you like our products and services, please help us by posting your review here.

malaybiswal
Posts: 2
Joined: Mon Mar 02, 2015 9:35 am
Contact:

Re: About Question com.enthuware.ets.scjp.v6.2.493 :

Post by malaybiswal »

How below is legal? I1 and I2 are 2 interfaces and there is no relationship between them .
I2 i2 = (I2) i1;

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

Re: About Question com.enthuware.ets.scjp.v6.2.493 :

Post by admin »

There is no need for a relationship between interfaces because a class can implement multiple interface. For example, i1 could point to an object of a class that implements I1 as well as I2, therefore, the compiler has to allow I2 i2 = (I2) i1;
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 27 guests