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.
1. [ Java ] casting
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.
test text
1. [ C# ] casting
The sample code shows Point p being cast to an
Object then cast again
back to a Point.
test text
2. [ Java ] 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.
test text
2. [ C# ] 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.
test text
3. [ Java ] Test before casting
We can check to see if the cast is going to work using
instanceof.
test text
3. [ C# ] Test before casting
We can check to see if the cast is going to work using
is.
test text