Final Constructs

BoxLang supports the usage of final constructs for three contexts:

  • Classes

  • Methods

  • Variables (Constants)

Final modifiers disallow the modifications to the source code to maintain stricter programming constructs. This would be used when you do not want to allow code to override your class or function or variable. This can be a great asset if you are building libraries, frameworks or APIs that require fine granular control of how they can be extended or used.

Final Classes

Classes can be declared as final, meaning they cannot be extended (inheritance) by other classes. This is the ultimate code reuse blocker! However, a final class CAN extend other classes.

final class{}

final class extends="MyService"{}

Unlike abstract a function can be final even if the class is not final.

Final Functions

Functions within a class can also be declared as final. Final methods cannot be overridden by sub-classes. Final methods can be used to limit the extent to which sub-classes redefine the behavior of the parent classes.

class BaseUtil{

    final function getFile(){
        return getCurrentTemplatePath();
    }

}

// Throws exception due to final method being overriden.
class extends="BaseUtil"{
    function getFile(){
         return "hijacked";
    }
}

Final Variables

Variables declared as final are ensured to be constants for the rest of the execution process. The value of that final variable cannot be modified post-construction of the class. Usually these constructs are used in variables defined in the pseudo-constructor.

class{
    final static CACHE_KEY = "cb_";
    final NAME = "John Majano"
    NAME = "Lui Majano" // Throws a final variable exception

    final DETAILS = { "age" : 1 }
    DETAILS[ "nickname" ] = "Johnny Bravo" // Allowed
    DETAILS = {} // Disallowed

}

Usually, final variables should be in uppercase to denote them as contstants as per Java conventions and best practices.

Last updated

Was this helpful?