Here, we will understand the concept of method overriding using the PHP program. In the method overriding, we can define a method with the same name in the parent and child class.
The source code to demonstrate the method overriding is given below. The given program is compiled and executed successfully.
<?php
//PHP program to demonstrate the method overriding.
class ParentClass
{
public function Method()
{
printf("Parent::Method() called<br>");
}
}
class Child extends ParentClass
{
public function Method()
{
printf("Child::Method() called<br>");
}
}
$ParentObj = new ParentClass();
$ParentObj->Method();
$ChildObj = new Child();
$ChildObj->Method();
?>
Output:
Parent::Method() called
Child::Method() called
Explanation:
In the above program, we created two classes ParentClass and Child and we inherited the ParentClass into Child class. Both classes contain a method with the same name. It means we have overridden the method Method().
At last, we created the objects of both classes and called the methods using objects that will call methods according to objects and print appropriate messages on the webpage.
Program/Source Code:
The source code to demonstrate the method overriding is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created two classes ParentClass and Child and we inherited the ParentClass into Child class. Both classes contain a method with the same name. It means we have overridden the method Method().
At last, we created the objects of both classes and called the methods using objects that will call methods according to objects and print appropriate messages on the webpage.
need an explanation for this answer? contact us directly to get an explanation for this answer