Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Multiple Inheritance and Polymorphism?

What is the difference between Multiple Inheritance and Polymorphism?

In a Book I red a line saying

there is no support for multiple inheritances at class level. This means you can't extend more than one class at a time.

Which is contradicting the concept of Polymorphism, described in the same book as

polymorphism is the process of creating several objects from specific base classes

Now if Multiple Inheritance is not allowed in PHP then how the Polymorphism is allowed?

like image 395
OM The Eternity Avatar asked Apr 23 '10 06:04

OM The Eternity


2 Answers

Like Ikke said, Multiple Inheritance has nothing to do with Polymorphism.

If I could draw a class diagram, Multiple Inheritance looks like this:

Base A    Base B
  ^         ^
   \       /
    \     /
     Child

So, the class Child would inherit both attributes and behaviours from both classes. Many languages like Java and PHP don't allow this, but Python does.

Polymorphism, on the other hand, is when you can abstract out a specialisation. First of all, class diagram:

     Animal
     ^    ^
    /      \
   /        \
 Cat        Dog

And you may do the following:

// Assuming we have a pack of animals
// This is Java
for (Animal pet : pack)
    pet.speak();

Each pet will say different things depending on the implementation.

like image 158
Xavier Ho Avatar answered Oct 13 '22 00:10

Xavier Ho


Multiple inheritance means an object inherits from two different parent classes. A ProgrammerBicyclist is both a Programmer and a Bicyclist. The problem arises when the Programmer class defines its member data favorite_activity as hacking while a Bicyclist also has favorite_activity, but it's riding. If you ask a ProgrammerBicyclist what her favorite_activity is, what's the correct answer?

Polymorphism deals with the behavior of objects. It lets you tell an object to do something and have the resulting action depend on the object's class, even if you don't know exactly what that is. So you come across a Person, though you don't know if it's a Programmer or a Cook, and you tell her to perform_your_job(). If it's a Programmer she will write code, if it's a Cook she will make a meal, but you don't have to specifically tell her to write_code() or make_a_meal().

like image 45
Paul Richter Avatar answered Oct 12 '22 23:10

Paul Richter