PHP

Preventing Inheritance and Overriding

A need to prevent some methods or classes from being inherited might arise in my object hierarchy. For example, I might want a way to prevent people from overriding the get_ProductID method in my Product class.

In its long-running tradition of solving my problems, PHP also provides a solution for this. By prefixing a method with the final keyword, you can prevent inheriting classes from overriding it and implementing their own version. I can modify my Product class as follows:

<?php
  abstract class Product
  {
    // etc.
    //
    // nobody can override this method.
    //
    final public method get_ProductID()
    {
      return $this->id;
    }
    // etc.
  }
?>

You may be scratching your head and wondering how a class can be abstract but have final methods that nobody can override. The answer is that an abstract class can still contain some implementation, but somebody has to extend it and implement the unimplemented portion defined by the abstract methods. The implemented portion of the class can include methods that cannot be overridden, as indicated by the final keyword.

Inheriting classes can still access and call these methods; they just cannot include them in the set of things they extend, modify, or reimplement.

Classes can also be declared as final, which means that nobody is allowed to inherit from them. You might see this if you have a User object and an inheriting AdministratorUser object with special privilegesyou might choose to declare the AdministratorUser object as final to prevent others from inheriting it and any of its special privileges.

by BrainBellupdated
Advertisement: