Marty Wallace
Marty Wallace

Reputation: 35776

Isn't polymorphism just a side effect of inheritance?

Im learning about oop just now and am struggling with the difference between inheritance and polymorphism.

If i understand correctly, inheritance defines a type hierarchy and the relationship between classes. Child classes inherit behaviour from the parent class and can provide specialised behaviour of any public interface on the parent.

Polymorphism is that these child classes can provide their own behaviour while still adhering to the parent interface.

This is the same thing isnt it?

Upvotes: 10

Views: 1763

Answers (3)

Grozz
Grozz

Reputation: 8435

Inheritance could also be used (not considered a good practice anymore) to inherit and extend functionality.

class MovableObject {
  protected: // usable in subclasses
    position: Point;

  public:
    void Move(Vector diff) { position += diff; }
}

class Car: private MovableObject { // private inheritance hides the interface
  private:
    float fuelLeft;

  public Drive(Vector diff, float fuelSpent) {
    Move(diff);
    fuelLeft -= fuelSpent;
  }
}

Of course, this is not the best class design and it isn't meant to be, but it illustrates how you can have inheritance without polymorphism.

Upvotes: 0

Tomas
Tomas

Reputation: 59555

You are correct that in most OO languages, inheritance and polymorphism go one with another. But:

  1. Polymorphism and Inheritance both illustrate different aspects. Polymorhpism shows how the types can stand one for another in operations, while the inheritance shows the relationship between the types.
  2. Polymorphism and Inheritance don't have to go together in general. If you look at integer and float numbers for example, there all of them can stand at the same places of arithmetic expression, so it is in fact polymorphism, but there is no inheritance. Also, inheritance is possible without polymorphism.

Upvotes: 11

user3585122
user3585122

Reputation: 93

The best way to look at it is that polymorphism is possible thanks to inheritance. Inheritance defines the hierarchy and the is-a principle, polymorphism can be achieved because of this.

Upvotes: 2

Related Questions