• Post Reply Bookmark Topic Watch Topic
  • New Topic

problem understanding inheritance  RSS feed

Angela lewis
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Olivier Lambert
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It means that class B is a specialisation of class A.

For example. A is Vehicle and B is Car.

B is a A
a Car is a Vehicle


A is not B
a Vehicle is not a Car

So you can assign a Car object into a Vehicle reference, but not a Vehicle object into a Car reference.

I hopes it can help you
Gian Franco
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
. 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
, but you can't say you can
play all instruments like they where a

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

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

HTH, cheers,

Gian Franco
[ June 11, 2004: Message edited by: Gian Franco Casula ]
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!