Upcast is the conversion of a derived type to a super-type. This doesn't require any explicit casting:
Base base = derived;
Downcast is the conversion of a super-type to a derived type. This require explicit casting:
Vehicle car = new Car(); Car car2 = (Car)car;
If I remove the casting I get a compilation error.
If the casting is wrong I get a runtime error. For this reason "instanceof" is used before a downcast:
if(car instanceof Car) { // continue...
Any other conversion different than downcast or upcast for objects generate a compile error or a runtime error.
The same rules apply to primitives, with the difference you can't use "instanceof" and you can sometimes convert between inconpatible types with a loss of information:
int a = (int)15.5f;
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.