what is overriding polymorphism in OOP. Can please give example in php

206 views Asked by At

I know what is polymorphism. But came accross overriding polymorphism. what is that and when does it needed?

1

There are 1 answers

1
Shankar Narayana Damodaran On

Glad to hear that you know what is "Polymorphism".

Let me explain you what is "Overriding" in Polymorphism.

Say you have a class called.. Bird

class Bird
{
    public function fly()
    {
        echo "I can fly";
    }
}

I have put up a method called fly() , which is a common trait for a Bird. (Let's see.. O.o) . I have put up like every bird can fly. Well ok..

Let us have another class called Sparrow which extends the Bird class

class Sparrow extends Bird
{

}

Since it extends the Bird class, you can directly access the method fly() like this..

$sparrow = new Sparrow();
$sparrow->fly();// "prints" I can fly

Well now, Let us have another class called Duck that extends the Bird class (Assuming... Ducks don't fly), So we are ought to access the fly() it would print "I can fly" [We don't need that , so in this case we need to Override the method]

Overriding the method !

class Duck extends Bird
{
    public function fly()   //Method Overriding
    {
        echo "I cannot fly";
    }
}

Eventually if you do this.. you will get like this..

$duck = new Duck();
$duck->fly(); // "prints" I cannot fly

This is somewhat a basic explanation of "Method Overriding".