This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I am having serious problems understanding inheritance.
I know this will give a compile time error because can't assign a broader type to a narrower type. But i somehow can't understand the reason for this.
B extends from A
doesn't that mean B will have whatever A has and B may have even more. So that means B is bigger than A.
Then why can't we assign b = a
i know i am getting it all wrong but can't really get it right. I can't make out how to visualize a subclass and a super class. Is subclass a bigger container or superclass a bigger container or something else. please help
It's easier if you look at inheritance from a real-life perspective, since that's what object orientation strives to model as closely as possible.
Suppose you have the class of musical instruments. You know you can play them. But when it comes to the specific instrument like flute, guitar, drums the way you play them is quite different.
So you can say you play a musical instrument, but you can't say you can play all instruments like they where a guitar.
musical instrument is generic and flute, guitar, drums are specific.
Taking this back to Java this means that the superclass musical instrument can't be downcasted implicitly. So why can you downcast it explicitly you might ask?
Explicit downcasting is allowed, because you are actually telling the compiler that the superclass reference might refer to a subclass reference at runtime, so the musical instrument might be a guitar for example.
If at runtime the superclass reference is not referring to a subclass instance but to a superclass instance you will get the infamous ClassCastException when the downcast is actually performed, because it's as if you are saying: take a generic musical instrument and use it like a guitar
Gian Franco [ June 11, 2004: Message edited by: Gian Franco Casula ]