What is method overloading and method overriding

Method Overloading and Method Overriding are two important concepts in object-oriented programming that allow developers to create more flexible and reusable code.

Method Overloading

Method overloading occurs when multiple methods in the same class have the same name but differ in the number or type of their parameters. This allows the same method to handle different types of inputs.

Example of Method Overloading in PHP:

<?php class MathOperations { public function add($a, $b) { return $a + $b; } public function add($a, $b, $c) { return $a + $b + $c; } } $math = new MathOperations(); echo $math->add(5, 10); // Outputs: 15 echo $math->add(5, 10, 15); // Outputs: 30 ?>

Method Overriding

Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass must have the same name, return type, and parameters as the method in the superclass.

Example of Method Overriding in PHP:

<?php class Animal { public function makeSound() { return "Some sound"; } } class Dog extends Animal { public function makeSound() { return "Bark"; } } $dog = new Dog(); echo $dog->makeSound(); // Outputs: Bark ?>

method overloading method overriding object-oriented programming PHP examples programming concepts