Keyword Final - leonard-thieu/monkey GitHub Wiki
Declares that a class may not be extended or that a method may not be overridden.
Syntax
Class Identifier [ < Parameters > ] [ Extends Class ] [ Implements Interfaces ] [ Final ] Declarations... End [ Class ]
Method Identifier : ReturnType ( Parameters ) [ Property ] [ Abstract ] [ Final ] Statements... End [ Method ]
Description
The Final modifier can be used in two contexts:
- Classes - the Final keyword at the end of a Class statement declares that the class may not be extended by other classes;
- Methods - the Final keyword at the end of a Method statement declares that a method may not be overridden (in an extended version of a non-Final class).
The examples below should help to clarify these cases.
See also
Examples
In this case, we try to extend the Dog class to create a Doberman class; however, this is forbidden due to the Final keyword in the Class statement.
This example will intentionally generate an error
.
' Runnable example
Class Dog Final
Method Bark ()
Print "Woof!"
End
End
Class Doberman Extends Dog
' Think I'll make my own Dog!
End
Function Main ()
Local d:Doberman = New Doberman
End
In the example below, Dog can be extended (no Final modifier); however, we have stated that the Bark method may not be overridden, again, using the Final modifier.
This example will intentionally generate an error
.
' Runnable example
Class Dog
Method Bark () Final
Print "Woof!"
End
End
Class Doberman Extends Dog
Method Bark ()
Print "RRGGGHHHRRRGHGHWWRRRRR!!!"
End
End
Function Main ()
Local d:Doberman = New Doberman
d.Bark
End
Note that in both cases, no error will be flagged unless (in the first example) you try to create a Doberman, or (in the second example) call the erroneously overridden method.