Final Class :

A final class is a class that cannot be extended. To declare a class as final, you need to prefix the 'class' keyword with 'final'.

example:
	<?php
	final class BaseClass {
		public function myMethod() {
			echo "BaseClass method called";
		}
	}
	//this will cause Compile error
	class DerivedClass extends BaseClass {
		public function myMethod() {
			echo "DerivedClass method called";
		}
	}
	$c = new DerivedClass();
	$c->myMethod();
	?>
Description :

In the above example, BaseClass is declared as final and hence cannot be extended (inherited). DerivedClass tries to extend from BaseClass and hence the compiler will throw a compile error.

Final Methods :

A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the 'final' keyword.

example:
	<?php
	class BaseClass {
	    final public function myMethod() {
		    echo "BaseClass method called";
	    }
	}
	class DerivedClass extends BaseClass {
	    //this will cause Compile error
	    public function myMethod() {
		    echo "DerivedClass method called";
	    }
	}
	$c = new DerivedClass();
	$c->myMethod();
	?>
Description :

In the above example, DerivedClass extends from BaseClass. BaseClass has the method myMethod() declared as final and this cannot be overridden. In this case the compiler causes a compile error.

When to declare a class as final :

You should declare a class as final when you think that your implementation of that class should not change in the derived class. You should do this mainly for Utility classes where you don't want the behavior/implementation of your class to change.

When to declare a method as final :

You should declare a class method as final when you think that the method you develop contains necessary functionality to support your application and any modification or change to the functionality can cause unexpected errors/bugs.

Questions for Final

  1. What is final class?Explain with example?
  2. What is final method?Explain with example?
  3. When to declare a class as final?Explain with example?
  4. When to declare a method as final?Explain with example?
After editing Click here:
Output:
Hello World