Java - Interview Questions - Explain The Code - Polymorphic Casting

Fruit fruit = (Apple) obj;

* assuming that the code compiles fine.

Q1. What is the type of obj ?

Possible Ans. If this code compiles, It means obj and Apple are related.

Either obj is the object of Apple
or obj is a reference of class that extends Apple
or obj is a reference of class that implements Apple
or obj is a reference of parent class of Apple 
or obj is a reference of interface that Apple implements.

Q2. Is Fruit the parent class of Apple ?

Possible Ans. We cannot make that out with this code alone, Fruit could be a class or an interface. The only thing sure is that Fruit and Apple are related.

Q3. What about obj class ? Is that related to fruit ?

Possible Ans. Yes but that could be transitive relation i.e Class of obj is related to Apple and Apple is related to Fruit.

Q4. Assuming that obj class is the parent of Apple , What kind of casting is this ?

Possible Ans. It's Down casting.

Q5. Following up with Q4, Can this throw any exception ?

Possible Ans. Yes this can throw ClassCastException depending on what obj holds during runtime and if that can be casted to Apple.

Q6. What if its opposite , Apple is the parent of obj Class, Can it still throw ClassCastException ?

Possible Ans. No, Upcasting never throw ClassCastException.

Q7. Can Fruit , Apple and obj's type be all interfaces ?

Possible Ans. Yes.