top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of final keyword?

+5 votes
767 views
What is the use of final keyword?
posted Nov 9, 2016 by Vrije Mani Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

Since you tagged it as PHP so answering in context of PHP

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Note: Properties cannot be declared final, only classes and methods may be declared as final.

Example 1:
class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
   public function moreTesting() {
       echo "ChildClass::moreTesting() called\n";
   }
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()

Example 2:
final class BaseClass {
   public function test() {
       echo "BaseClass::test() called\n";
   }

   // Here it doesn't matter if you specify the function as final or not
   final public function moreTesting() {
       echo "BaseClass::moreTesting() called\n";
   }
}

class ChildClass extends BaseClass {
}

// Results in Fatal error: Class ChildClass may not inherit from final class (BaseClass)

Credit: http://php.net/manual/en/language.oop5.final.php

answer Nov 9, 2016 by Salil Agrawal
Final essentially means that the variable et will not be reassigned at any point and will remain around. This means that inner classes, like your listener, can trust that it wont be reassigned by some other thread which could cause all kinds of trouble.check this useful link to know more.
https://www.mindstick.com/Articles/12093/the-final-keyword-final-classes-and-variables
http://www.cs.unc.edu/~hedlund/programming/coding/bulletproof/UseOfFinal.html
...