What is the difference between multiple inheritance and polymorphism?

What is the difference between multiple inheritance and polymorphism?

In the book I'm a red line saying

there is no support for multiple class-level inheritance. This means that you cannot extend more than one class at a time.

This contradicts the concept of polymorphism described in the same book as

Polymorphism

is the process of creating multiple objects from specific base classes

Now, if multiple inheritance is not allowed in PHP, then how is polymorphism allowed?

+4
source share
3 answers

As 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 Child class inherits both attributes and behavior of both classes. Many languages, such as Java and PHP, do not allow this, but Python.

Polymorphism , on the other hand, is when you can ignore specialization. First of all, the class diagram:

  Animal ^ ^ / \ / \ Cat Dog 

And you can 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.

+18
source

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

Polymorphism deals with the behavior of objects. This allows you to tell the object to do something and have a resultant action depending on the class of the object, even if you don’t know exactly what it is. Thus, you are confronted with the Person, although you do not know if he is a Programmer or a Cook, and you tell her to perform_your_job() . If she is a programmer, she will write the code, if he cook prepares the food, but you don’t need to tell write_code() or make_a_meal() .

+3
source

These two have very little in common with each other.

Multiple inheritance is what is static after compile time / runtime. Polymorphism is a method in which only at runtime it is determined which method is called by a subtype.

PHP does not allow multiple inheritance.

+1
source

Source: https://habr.com/ru/post/1307755/


All Articles