Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1458 :

Posted: Sat Feb 15, 2020 2:13 pm
by FanaticuS
Hi,

I have a question about option 5 and it's explanation:

5)
ArrayList<Vehicle> al5 = new ArrayList<>();
Drivable d2 = al5.get(0);

Explanation:
"Since a Vehicle is not a Drivable, you cannot assign an instance of a Vehicle to variable of type Drivable without a cast"

If Vehicle isn't connected to Drivable then how can we assign an instance of a Vehicle to variable of type Drivable with a cast? Or there is a small error in the explanation?

Re: About Question enthuware.ocajp.i.v8.2.1458 :

Posted: Sat Feb 15, 2020 11:38 pm
by admin
No, the explanation is correct.
Drivable is an interface. Although Vehicle does not implement Drivable, it is possible for a subclass of Vehicle to implement Drivable. The compiler knows that a variable of type Vehicle could actually point to a Drivable object. (In this case, the list may contain such objects) That is why it allows the assignment with a cast.