posted 18 years ago
Just remember that casts can't change anything; they only tell the compiler what it doesn't know will be happening at runtime. So if you've got an object whose class is Child, and Child is a subclass of Parent, the following are all legal;
Child c = new Child();
Parent p = new Child();
Child c2 = (Child) p;
Parent p2 = (Parent) c; // Cast is legal, but not needed
Given that Parent has another subclass named Kid, then the following are all illegal:
Kid k = new Kid();
Parent p = new Parent();
Child c = new Child();
Child c2 = (Child) k; // Won't compile because a Kid is never a Child
Child c3 = (Child) p; // Will fail at runtime, because p points to a Parent not a Child
Kid k2 = (Kid) c;
Kid k3 = (Kid) p;
So the legal casts are the ones that tell the truth about the real classes of the objects; the illegal ones are the ones that lie.