Using Final to Prevent Overrides and Extension

In a previous post about inheritance, I showed you how to extend a class.   One aspect of extending classes that wasn’t fully covered was the idea of overriding a method in a class. You can override a method (function) from the base class by simply redefining the method in the child class.

In the following example, if you instantiate the Child class and call the hello() method, you will get the message ‘Hello World has been Overridden!’.  There are times though, when you do not want a method to ever be overridden.  There may even be cases where you do not want a class to be extended.

Let’s say for example we have a custom class for accessing and manipulating information from an ODBC connection to a SQL Server database.  We will call this class MsSqlObject. In that class there is a method to retrieve a single record from a table and put it into an associative array where the array key is the field name of the database table.  The method is called getRecord().  Most of our business object classes extend the MsSqlObject class to provide convenient access to the database.  In this case, we would not want the user to accidentally override the getRecord() method, because it could break the application within the extended class if other methods are calling the getRecord() method.

This is where the “final” keyword comes into play.

By adding the final keyword, we have assure that the method cannot be overridden, and if someone does try to override the method, the will see the following error:

“Fatal error: Cannot override final method MsSqlObject::getRecord() in …”

Similarly, classes can be defined as final to prevent them from being extended.  This may be useful if you want to prevent a user from extending a class.  An example might be a utility class that you want left as-is.  The final keyword makes is clear that the developer did not intend for the class to be inherited/extended.

Hope this helps



, ,

Comments are closed.