PHP program to demonstrate the final keyword

Here, we are going to demonstrate the final keyword in PHP.
Submitted by Nidhi, on November 21, 2020

Here, will create a class that contains a final method Method(), and as we know that we cannot override a final method, that's why it will generate a syntax error.

Program/Source Code:

The source code to demonstrate the final keyword is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the final keyword.
class ParentClass
{
    final public function Method()
    {
        printf("Parent::Method() called<br>");
    }
}
class Child extends ParentClass
{
    final public function Method()
    {
        printf("Child::Method() called<br>");
    }
}

$ChildObj = new Child();
$ChildObj->Method();
?>

Output:

PHP Fatal error:  Cannot override final method ParentClass::Method() 
in /home/main.php on line 16

Explanation:

In the above program, we created a class that ParentClass that contains a method, which is declared as final, and then we inherited the ParentClass into Child class and override the method, but as we know that we cannot override a final method, that's why above program will generate a syntax error.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.