Reputation: 35776
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
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
Reputation: 59555
You are correct that in most OO languages, inheritance and polymorphism go one with another. But:
Upvotes: 11
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