In this part we will learn on the following topics:
· What is final class?
· When to declare Final class?
· What is final method?
· When to declare final method?
What is final class?
Code Implementation:
<?php
final class text { // class text is final
function term() {
echo "hello!! i am parent class.";
}
}
class child extends text
{
function mylife()
{
echo "hello!! i am child class.";
}}
$obj = new text();;
$obj->term();
?>
Code output:
So, from above example it concludes that final keyword is used to prevent a class from being inherited. In other words, final class can never be inherited.
What is final method?
As in case of inheritance derived class inherits all the methods or function of base class (parent class). There can be a situation where you want to prevent a function or method from being inherited by child class. This can be done by using final keyword preceded by function name. Following is an example which shows how to use final keyword in your method:
Code Implementation:
<?php
class text {
final function term() {
echo "hello!! i am parent class.";
}
}
class child extends text
{
function term()
{
echo "hello!! i am child class.";
}}
$obj = new text();;
$obj->term();
?>
Code output:
So, from above example it concludes that final keyword is used to prevent a class method or function from being inherited. In other words, final method of parent class can never be overridden by child class.
Following is an example to show the correct way to use final keyword:
Code Implementation:
<?php
class text {
final function term() {
echo "hello!! i am parent class.";
}
function term1() {
echo "hello!! i am parent class second method.";
}
}
class child extends text
{
function term1() {
echo "hello!! i am child class second method.";
}}
$obj = new child();
$obj->term();
$obj->term1(); // display the child class method
$obj1 = new text();
$obj1->term1(); // display the parent class method
?>
Code Output:
hello!! i am parent class.
hello!! i am child class second method.
hello!! i am parent class second method.
When to use final class?
A class should made final when you want your class should never be changed by derived class or child class. This is done mainly in utility classes where you don’t want the behavior or implementation of your parent class gets changed.
When to use final method or function?
A class function is declared as final when your function contains necessary functionality to support application and any change or modification to your function can cause unexpected errors or bugs.
marcel ethan
28-Mar-2017