1

Imagine that we have a class Animal that extends to three other classes: Dog, Cat, Bird.

This animal class has a talk() and move() function. The talk function outputs "Animal talking" and the move function outputs "Animal moving".

For a dog, this is "Dog moving" and "Dog eating". For the Cat and Bird class, this difference is paralleled "Cat moving" etc.

Now, because of polymorphism, if I do

Animal charlietheBird = new Bird()

and then call in

charlietheBird.talk()

it will output

Bird talking

because the output is determined at runtime since the compiler knows that charlie is a type of Animal of the class Bird.

HOWEVER!!

I can simply do

Bird charlietheBird = new Bird();

and then calling charlietheBird.poop(); will give the same output, because the method would have been overridden.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
silenceislife
  • 161
  • 1
  • 7
  • 5
    Polymorphism is a concept. Inheritance (along with virtual functions) is the technical means for implementing that concept. So the question in the title is kinda irrelevant. – barak manos Feb 06 '17 at 05:47
  • 1
    http://stackoverflow.com/questions/6308178/what-is-the-main-difference-between-inheritance-and-polymorphism - this will be helpful – MSD Feb 06 '17 at 05:54
  • You are basically correct. The advantage of declaring some bird an `Animal` comes when you have 234 cats, a dog and 5000 birds in your program if you may sometimes want one of them to talk or move without caring the exact type of animal you are dealing with. – Ole V.V. Feb 06 '17 at 07:26
  • @silenceislife I believe your question roughly translates to *Why do we need Polymorphism if we have Inheritance*. See my answer for a detailed explanation of what *Polymorphism* can do. – Chetan Kinger Feb 06 '17 at 09:45
  • @barakmanos Isn't inheritance a concept too just like polymorphism? Or rather, isint polymorphism implemented, technically? Both polymorphism and inheritance require code to be structured in a particular way right? – Chetan Kinger Feb 06 '17 at 12:36
  • @CKing: Inheritance is a technical term AFAIK. I would go even farther, saying that it's a keyword, but that wouldn't be completely accurate, because inheritance is achieved via a combination of keywords (to be even more accurate, by 3 different combinations of keywords - `class / public`, `class / protected` and `class / private`). But it is nevertheless a technical means which (together with virtual functions) allows you to implement different design patterns and other conceptual ideas, with *polymorphism* being the primary (and most general) concept. – barak manos Feb 06 '17 at 12:41
  • @barakmanos I don't follow or agree. Inheritance is as much a concept as polymorphism is. Just like there is a standard way to implement inheritance, there is a standard way to implement polymorphism. These are the building blocks of an object oriented language. Both require arranging code in a specific way using language specific keywords. – Chetan Kinger Feb 06 '17 at 13:02
  • @CKing: I cannot say more than what I've said in the original comment, and with more details in the one following your question, in order to persuade you... In my perspective, *polymorphism* is the concept of generalizing objects for certain purposes, and specializing them (as in "the opposite of generalizing") for other purposes. Inheritance and virtual functions are just the implementation tool. I suppose that it can be viewed as a matter of terminology, so that's my terminology (and we don't have to agree on it). – barak manos Feb 06 '17 at 13:24
  • @barakmanos Fair enough. I don't oppose anyone having their own view on things. That said, the general consensus considers both polymorphism and inheritance to be concepts/features of OOP languages. Our very own OOP tag explicitly mentions Polymorphism and Inheritance side by side as features. And your comment did not answer the question being asked. The OP simply wants to know why we need Polymorphism when we have inheritance and not what's the difference between them. – Chetan Kinger Feb 06 '17 at 13:31
  • If you are interested in the differences between polymorphism and inheritance, you will want to see [Is polymorphism possible without inheritance?](http://stackoverflow.com/questions/11732422/is-polymorphism-possible-without-inheritance) too. – Ole V.V. Feb 06 '17 at 13:31
  • @CKing: According to my view (and as explained in the original comment), the question in the title is simply irrelevant. Now, if you don't oppose my view, then I don't see the point in saying that it "did not answer the question being asked". BTW, I believe that the post given by Ole V.V in the comment above supports my original argument (of *polymorphism* being a concept and *inheritance* being a "tool"). – barak manos Feb 06 '17 at 13:59
  • @barakmanos I don't see how the linked post talks about polymorphism being a concept. For me, OOP is a paradigm and inhertiance and polymorphism are both concepts defined in this paradigm. But I see your point of view too so it just boils down to agreeing to disagree. My bad for restarting the discussion again when it had already ended on the same note earlier :). I propose to end it at this comment. – Chetan Kinger Feb 06 '17 at 14:46

3 Answers3

4

What can polymorphism do that inheritance can't?

The real advantages of Polymorphism can be seen at runtime rather than compile time. Polymorphism allows you to substitute one implementation for another without the need to change the code that uses it. Let's take your example of the Animal hierarchy. Let's say you have a Vet that knows how to perform health checkups on any animal (Yup he's a supervet).

class Vet {
   private Animal animal; 
   public Vet(Animal animal) {
      this.animal = animal;
   }

   public void perfromCheckup() {
      animal.talk();
      animal.poop();
   }
} 

You can now say :

Vet vetWithBird = new Vet(new Bird());
Vet vetWithDog =  new Vet(new Dog());
vetWithBird.performCheckup();
vetWithDog.performCheckup();

Notice how you can tell the Vet to perform a checkup on a Bird or a Dog or any other animal for that matter without needing to change your Vet class. At runtime, the Dog would bark when it goes for a checkup and the Bird would tweet when it goes for a checkup. Imagine if instead of Animal, the Vet had a Bird reference :

class Vet {
   private Bird bird; 
   public Vet(Bird bird) {
      this.bird = bird;
   }

   public void perfromCheckup() {
      bird.talk();
      bird.poop();
   }
} 

The poor Vet is now only going to be able to work with a Bird. Tell your Vet to work with a Dog and he will reject this right away.

Vet vetWithBird = new Vet(new Bird()); //Works fine. Vet likes birds.
Vet vet = new Vet(new Dog())// compilation error. Sorry I don't like dogs.

In summary, Polymorphism allows you to substitute subclass instances where a super-class reference is used. Inheritance allows you to inherit code from a parent class and possibly redefine that behavior in subclasses so that your code can take advantage of it at runtime through Polymorphism

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
2

Inheritance refers to a feature of Java programming that lets you create classes that are derived from other classes. A class that's based on another class inherits the other class. The class that is inherited is the parent class, the base class, or the superclass.

Polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.

You can find more information in Objects and Java by Bill Venners Chapter 7: Polymorphism and Interfaces

Elnaz
  • 1,095
  • 1
  • 12
  • 30
  • I don't believe the OP is asking for the difference between the two. The question is *what can polymorphism do that inheritance can't?*. This roughly translates to *show me a use case where I need polymorphism and inhertiance won't suffice*. – Chetan Kinger Feb 06 '17 at 09:58
  • Also, this answer has been worded exactly the same way as [this](http://stackoverflow.com/a/6308243/810077). Now I am curious about whether this is an established terminology in some publication/book? – Chetan Kinger Feb 08 '17 at 07:12
  • It's a generic definition with differences. I added more info + a good reference! Your answer is good enough with a complete summery :-) – Elnaz Feb 08 '17 at 07:46
2

Inheritance supports Polymorphism but Polymorphism does not depend on Inheritance.

You gave an example how to achief Polymorphism via Inheritance.

But you could look at it differently:

There is an interface for the concept of moving:

interface Movable{
  void move();
}

Animals may implement this interface:

class Dog implements Movable {
  @Override
  public void move(){
    // move the animal
  }
}

but some fungis can also move:

class SlimeMold implements Movable {
  @Override
  public void move(){
    // move the animal
  }
}

There is hardly to find an "is a" relationship between those two which could be expressed by inheritance, but when both implement the same interface we can still apply Polymorphism on them:

Collection<Movable> movables = new HashSet<>();
movables.add(new Dog());
movables.add(new SlimeMold());
for(Movable movable : movables)
   movable.move();
Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • A `Dog` is a `Movable` object. – Chetan Kinger Feb 06 '17 at 09:41
  • @CKing maye I'd better called that interface *Mobile*? – Timothy Truckle Feb 06 '17 at 09:51
  • That's not the point I am making. Your `Dog` would still be `Mobile` and you would still be able to say `Dog` is a `Mobile` animal. Runtime Polymorphism (in the context of your answer) always depends on some kind of inheritance. I don't agree with the following line : *Polymorphism does not depend on Inheritance*. – Chetan Kinger Feb 06 '17 at 09:52