• Post Reply Bookmark Topic Watch Topic
  • New Topic

inheritance  RSS feed

 
Rupinder Bains
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why is inheritance seen as a key factor in object oriented software development?

Ive read up on it but still doesnt make any sense???
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The true power of inheritance is polymorphism.

Consider a parent class called Animal, and suppose it has a method called transportOffspring(). In this Animal class, the implementation of transportOffspring() might be to simply herd the offspring.

Now consider two classes that each inherit from Animal: One is Cat, which overrides transportOffspring() to carry by the scruff of the neck; and the other is Kangaroo, which overrides transportOffspring() to carry in the pouch.

Now suppose that we have another class called Veterinarian with a method called admit(Animal). Note that the type of the argument to admit() is the parent class, Animal. This way, we don't need a separate admit() method overloaded for each possible type of Animal -- and we won't need to modify the Veterinarian class each time we define a new Animal. So our code is robust. Now we can pass a Cat, a Kangaroo, or any other subclass of Animal to admit(Animal), and they will each be automatically upcast (through method-call conversion) to type Animal.

But now suppose that we call the transportOffspring() method on these Animals. We don't know whether it's a Cat or a Kangaroo or some other subclass -- all we know now is that it's an Animal. How will this Animal behave when we call transportOffspring()? We might expect that, since it's upcast to type Animal, it will invoke the parent method and herd its offspring. But instead, the Animal surprises us by either carrying by the scruff of the neck or carrying in a pouch, depending on whether its true runtime type is Cat or Kangaroo.

In other words, we are able to treat an object as one type (Animal), yet still have it behave like another (Cat or Kangaroo). Hence the "poly" in polymorphism.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rupinder,

You might like to read the "How my Dog learned Polymorphism" story in the JavaRanch Campfire Stories.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!