From Progzoo
Revision as of 18:43, 29 March 2009 by Andr3w (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.


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 is.

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