I1 and I2 don't necessarily need to have any is-a relationship. You can have a class that extends C3 and implements I1 as well, right? The compiler can see this possibility and accepts the code.
In case of your example, the type of a is U1 and you are trying to assign it to U2. But there is no way the variable a could ever point to an object of a class that satisfies is-a relationship to U1. The compiler figures this out and rejects the cast.
If you had something like this:
I1 a = null;
U2 b = (U2) a;
This is ok even if U2 does not implement I1 because the compiler knows that it is possible to write a class that extends U2 and implements I1. Therefore, it is possible for a to point to an object of a class that is-a U2. This proves that there is no need for I1 and U2 to have any is-a relationship between themselves.
HTH,
Paul.
About Question enthuware.ocajp.i.v7.2.1002 :
Moderator: admin
-
- Site Admin
- Posts: 10391
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
-
- Posts: 14
- Joined: Sat Dec 17, 2016 10:17 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1002 :
Oh, that makes perfect sense now. Thank you!
-
- Posts: 202
- Joined: Mon Apr 02, 2018 8:40 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1002 :
The explanation says:
but there are no objects, only references?This is valid because at run time i1 actually refers to an object that implements I2.
-
- Site Admin
- Posts: 10391
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.1002 :
You can cast null to any type. So even if there is no object, the JVM has no problem with the assignment.
Who is online
Users browsing this forum: Google [Bot] and 8 guests