it's because Q2 is a subclass of Test. You may assign an instance of class Q2 to a variable of type Test (as on line 22) since the conversion is up the hierarchy. But if you want to assign "down" the hierarchy a cast is needed. The cast tells the compiler that you know what you are doing. Remember that a variable of type superclass may reference any instance the type subclass, but not the opposite.
For instance, you have a hierarchy like this
where A is the superclass and B and C are the subclasses of A but are not related to each other. Look at the following code:
As you can see a and a1 are variable of type A. a points to an instance of B which is legal and a1 points to an instance of C which is legal too. BUT, if you don't provide a cast on the last line it means that you are trying to assign an instance of class C to a variable of type B which is not legal since B and C are not related by any way...
In your example, you have to write line 25 as follows
q = (Q2) t;
and this line tells the compiler that you are sure that the variable t will be holding at runtime an instance of class Q2 which is the case according to line 22.
I don't know if this is clear enough but let me know if not...
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for
Java 2 Platform