CK Tan

Greenhorn
+ Follow
since Apr 18, 2005
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by CK Tan

Hi,

As far as i know, type casting can be done only on primitive and reference that are related.

At compile time, compiler will check whether you are assigning a superclass type to one of its subclass type. If yes, an error will be thrown. By using the cast operator, i guess this step is bypass.

Then at run-time, the object referenced by the variable will be checked against the type in the cast operator. If they don't have a "is-a" relationship, an ClassCastException will be thrown. An object can only be cast to itself or its superclasses.

Thats explain why line 1, 2 and 4 have runtime exceptions. wawa is a superclass type variable and its referenceing its subclass, Cat. Clearly, Cat is not a SwarmThing or Racoon or Dog.

For line 5, i guess because the cast operator is an unary operator and it has higher percedence over the new keyword, the statement will try to cast the keyword New. This i am not so sure, is it a syntax error at compile time?

Cheers!