Classes & OOP: The 'final' Modifier

Roger PoonBy Roger Poon

JS++ Designer and Project Lead

In the context of virtual methods discussed in the previous section, the 'final' modifier allows us to form an even more correct specification.

When applied to overridden methods, the 'final' modifier allows us to specify that this method override is the last and cannot be further overridden. This prevents subclasses from further overriding the method. In fact, it can be good defensive programming to use the 'final' modifier instead of the 'override' modifier. We can then only resort to the 'override' modifier when we need to subclass and the compiler gives us an error telling us that we cannot further override a method previously specified as 'final'. This can help us prevent unforeseen circumstances and potential bugs in complex code.

With that said, let's change Cat.jspp and Dog.jspp to use 'final' instead of 'override'. Once again, for the sake of brevity, I'll only be showing the changes to Cat.jspp:

    external $;

    module Animals
    {
        class Cat : Animal
        {
            string _name;

            Cat(string name) {
                super("icofont-animal-cat");
                _name = name;
            }

            final void render() {
                $element.attr("title", _name);
                super.render();
            }
        }
    }
    

If you compile the code and observe the result, you should see it behaves exactly as if we used the 'override' modifier.

The 'final' modifier can also be applied to a class. When the 'final' modifier is applied to a class, it means the class can no longer be subclassed. In other words, further inheritance is prevented. For example, try declaring 'Cat' as 'final' and try to subclass it from main.jspp:

    import Animals;

    class Kitten : Cat {}

    Animal[] animals = [
        new Cat("Kitty"),
        new Cat("Kat"),
        new Dog("Fido"),
        new Panda(),
        new Rhino()
    ];

    foreach(Animal animal in animals) {
        animal.render();
    }
    

If you try to compile this code, you'll get an error because 'Cat' is 'final' and cannot be subclassed:

[ ERROR ] JSPPE0163: Cannot inherit from final class `Animals.Cat'

Please remove the 'final' modifier from Cat.jspp and remove the 'Kitten' class from main.jspp. This was just a demonstration. Make sure your project compiles before moving to the next section.