From Progzoo
Jump to: navigation, search

We sometimes need to cast from one class to another. We can only cast up or down the class hierarchy. As Object is at the top of the class hierarchy we can always cast to an object.

Casting down the hierarchy may result in a run time error.


Prior to Java 1.5 we had to cast to use a Hashtable or an ArrayList. Since 1.5 we do not need to do this.

The sample code shows Point p being cast to an Object then cast again back to a Point.

[Font] [Default] [Show] [Resize] [History] [Profile]

Incorrect casting

There is a danger of casting to incompatable type. When this happens we get a run time error.

The code shown compiles OK but fails at run time.

[Font] [Default] [Show] [Resize] [History] [Profile]

Test before casting

We can check to see if the cast is going to work using instanceof.

[Font] [Default] [Show] [Resize] [History] [Profile]