This content has been marked as final. Show 6 replies
You can cast a parent reference to a child reference, but if the object that reference points to isn't an instance of the child class, you'll get ClassCastException.
Casting doesn't change objects. It just says that a reference that was declared to be of one type should actually be treated as a reference to another type.
Parent p1 = new Parent(); // 1 Parent p2 = new Child(); // 2 Child c1 = new Parent(); // 3 Child c2 = new Child(); // 4 Parent p1 = (Parent)c1; // 5 Parnet p2 = (Parent)c2; // 6 Child c3 = (Child)p1; // 7 Child c4 = (Child)p2; // 8
2: Ok. Every Child IS-A parent.
3: Compile time error. A Parent object is not a Child.
5: Ok, because every Child IS-A parent, and the cast is unnecessary. (Though since 3 is illegal a compile time we wouldn't actually have this situation.)
6: Ok, and the cast is unnecessary, because every Child IS-A Parent.
7: ClassCastException at runtime. The object is not a Child.
vanilla_lorax wrote:Yeah I realised after I posted my answer was only directed against posted code and did not give a complete answer.
Quacked wrote:You can cast a Parent reference to Child IF the object it points to is a Child object (or if the reference is null).
So you can cast a Child to a Parent but you cannot cast a Parent to a Child.