Categories
Php Php Oops

Final Keyword

In Php we can use final keyword with Classes and Methods.

1. Final Classes Prevent inheritance

2. Final Methods Prevent Method Overriding

Final Classes: If we declared a class as final class then subclass can not be extended parent class.

	final Class Parent
	{
		public function show($a,$b)
		{
			$mul=$a*$b;
			echo "Multiplication of given no=".$mul;
		}
	} 

	class Child extends Parent
	{
		function show($a,$b)
		{
			$sum=$a+$b;
			echo "Sum of given no=".$sum;
		}
	}
		
	$obj= new Child();
	$obj->show(100,100);
	
Output Fatal error: Class Child may not inherit from final class (Parent) in C:xampp\htdocs\test\index.php on line 17

Final Methods: If we declared a method as final method then subclass can not be overriding parent class method.

class Parent	
{
	final function show($a,$b)
	{
		$mul = $a*$b;
		echo "Multiplication of given no=".$mul;
	}
} 
class Child extends Parent
{
	public function show($a,$b)
	{
		$sum = $a+$b;
		echo "Sum of given no=".$sum;
	}
}	 
$obj= new Child();
$obj->show(100,100);

Output Fatal error: Cannot override final method Parent::show() in C:xampp\htdocs\test\index.php on line 18

Categories
Php

Static Keyword

Categories
Php

Abstraction in php

Categories
Php

Inheritance in php

Categories
Php

Interface in php

Categories
Php

Namespaces in php