Originally posted by Sam Cooper:
Could some one please go over this casting example once again.
Any thoughts are greatly appreciated
Okay - here goes. Corey's synopsis 'o casting...
When dealing with two objects that are in an inheritance relationship, it is possible to use a child object wherever you expect a parent object. Take the following example:
A key to remember is that you can always use a child class wherever you can use a parent class. This is because the child class has an "is a" relationship with the parent. In this case, a Dog "is a" Animal. Therefore, you can use a Dog wherever an Animal is expected, like I did in line 1.
When you use an instance of a child class when the compiler is expecting an instance of a parent class, an implicit "widening" conversion is done. However, just like with Java primitives, this conversion doesn't work both ways. Let's continue the example from above...I'll just continue the code in main below:
Line 2 is illegal because I'm trying to use an instance of a parent class where an instance of a child is expected. An Animal is not a Dog - it might be a Cat, or a Bat, or a Rat (I'm such a poet). Therefore, the compiler forces us to say "Yes, the object a1 references is really a Dog and I'll take responsibility for anything that happens." That's what we're doing in line 3. The cast tells the compiler that we know that a1 references a Dog object. In this case, we're right a1 really does reference a Dog object, so this code will compile and run just fine. However, is a1 really referenced an Animal, this code would compile, but it would throw a CastClassException (which "is a" RuntimeException) when you tried to execute it.
So, those are the rules about casting parents and siblings. Now, let's look at how you cast and assign siblings. Look at the following code:
In this code, I'm casting a Dog to a Cat and vice versa.
THIS IS ILLEGAL! This code will not compile. A Dog is not a Cat and a Cat is not a Dog, even though they are both animals. In Java, siblings are not really related in any way.
So, that's what I know about casting. I hope that helps - if you have more questions, please ask.
Corey