Thomas A Davis wrote:So, Fred, if I understand what you said, that ANY subclass object can be cast into the super class type without losing any information? Is this correct? Thank you, Tom
I had loads of trouble with this coming from scripting languages. Like Fred said the key is that casting affects the object reference not the object itself.
The metaphor/analogy which always spoke to me was from Head First Java - (I would suggest the book strongly to someone coming from a procedural background) this isn't what they use in the book but this is how it is in my mind now when I think of casting/polymorphism:
Say you have a class
StandardTV which has five channels and five methods
selectChannel_1 - selectChannel_5 (bad OO design notwithstanding
).
I can say
StandardTV myStdTVref = new StandardTV()
On the right of the = I create a
StandardTV object. On the left of the = I create a
StandardTV reference.
myStdTVref is like a remote control for a
StandardTV, it tells me I have my five badly designed methods which I can use to pick channels 1-5.
Now I extend StandardTV to SuperTV with 140 channels and using my appalling OO design I give SuperTV 140 methods
selectChannel_1 - selectChannel_140.
Now I could say
SuperTV mySupTVref = new SuperTV()
mySupTVref is a remote with the 140 channels to pick from.
But I could also say
StandardTV mySupTVref = new SuperTV()
Now, I created (on the right of the =) a
SuperTV but I only pointed (on the left of the =) a
StandardTV reference at it so my remote only has the 1-5 channel methods on it. These work fine because my
SuperTV has those five channels, it just happens to have (extend) 135 more which I can't access at the moment. But the important thing is that just because the remote doesn't show the channels (methods) doesn't mean the TV doesn't have them. Later on I can cast
mySupTVref back to a
SuperTV reference and I can then access all those 140 channels*. The
SuperTV object never changed - I just took away and added buttons to the remote.
*Take care casting down to the subtype because if there is more than one subtype casting to the wrong one will stitch you - when you get here look at
instanceof to check what the object really is.
I don't know if this will help you but it is the way I managed to get it into my head. When you get it you'll see that it is just a duplicate of what Fred said really, just a different example.