Php Method Overriding

What is Php Method Overriding?

If child class has the same method and parameter as declared in the parent class, it is known as method overriding.

Note:-(i) Method overriding is used for runtime polymorphism.
(ii) The static method of the class can not be overridden.

Example:-
In the below example, All companies give to a fresher package according to company rule. TCS gives 3.2 lakh per annum and Oracle gives 4.2 Lakh Package per annum and some small company does not give money to employees.
(i) fresherPackage method of TCS class override the method fresherPackage of company class.
(ii) fresherPackage method of Oracle class override the method fresherPackage of company class.


<?php
class company {
	public function fresherPackage() {
		echo 0;
	}
}
class TCS extends company{
	public function fresherPackage() {
		echo 'TCS provide 3.2 Lakh per annum.';
	}
}
class Oracle extends company{
	public function fresherPackage() {
		echo 'Oracle provide 4.2 Lakh per annum.';
	}
}
$tcs_Obj=new TCS;
$tcs_Obj->fresherPackage();

$oracle_Obj=new Oracle;
$oracle_Obj->fresherPackage();
?>
Output:- TCS provide 3.2 Lakh per annum.
Oracle provide 4.2 Lakh per annum.

Php Method Overriding – Interview Questions

Q 1: What is method overriding in PHP?
Ans: Method overriding occurs when a child class provides its own implementation of a method already defined in the parent class.
Q 2: Which concept is required for method overriding?
Ans: Inheritance is required.
Q 3: Can access modifiers be changed while overriding a method?
Ans: Yes, but visibility cannot be more restrictive than the parent method.
Q 4: What keyword is used to call the parent method?
Ans: The parent keyword.
Q 5: Why is method overriding useful?
Ans: It allows child classes to customize or extend parent class behavior.

Php Method Overriding – Objective Questions (MCQs)

Q1. Method overriding occurs when ______.






Q2. Which access level allows overriding?






Q3. Method overriding is an example of ______.






Q4. Can a final method be overridden?






Q5. Parent class method can be accessed inside overriding method using ______.






Related Php Method Overriding Topics