开发者

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 inh开发者_如何学Ceritances 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 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.


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().


Those two have very little to do with each other.

Multiple inheritance is something that is static after compile time / runtime. Polymorphism is a technique where only on runtime actually is decided which method on a subtype is called.

PHP doesn't allow for multiple inheritance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜