Hi all,
Im trying to understand what the
Java checks for regarding illegal casts during compile time and runtime.
In this program, I've created four classes, AClass, BClass (which extends AClass), CClass (which extends BClass), and the Tester class. The Tester class creates an object,a, with reference to AClass, but instantiated with CClass. It then creates another object,b, with reference to BClass that holds the value (references the value?) of a copied object a casted into BClass...Finally, the code prints out BClass' i value.
As I understand it...in this statement
AClass a = new CClass(); <--- AClass is reference type and CClass is compile-time type. (Please correct me if wrong)
My Questions Are:
1) What does the Java compiler check for in regards to object assignment and casting? Does it just check to see if compile-time type assignments are valid?
2) What does the Java runtime environment check for in regards to object assignment and casting?
public class Tester {
public static void main(
String args[]) {
AClass a = new CClass();
BClass b = (BClass) a;
System.out.println(b.i);
}
}
class AClass {
int i = 5;
void method() {
System.out.println("Class A Method");
}
}
class BClass extends AClass {
int i = 6;
void method() {
System.out.println("Class B Method");
}
}
class CClass extends BClass {
int i = 7;
void method() {
System.out.println("Class C Method");
}
}
I apologize if this question is vague...
Thanks,
Dave
[ April 15, 2005: Message edited by: David Miranda ]