Final class variables
Using the final
keyword on class variables specifies that the variable can be set only
once, and only in the declared class. Subclasses cannot set the value
of a final class variable.
For example:
class TestABC {
final var _name : String = "John"
}
Optionally, you can use the final keyword on a class variable
declaration without immediately initializing the variable. If you do
not immediately initialize the variable in the same statement, all class
constructors must initialize that variable in all possible code paths.
For example, the following syntax is valid because all constructors initialize the final variable once in each code path:
class TestABC {
final var _name : String
construct() {
_name = "hello"
}
construct(b : boolean){
_name = "there"
}
}
The following code is invalid because one constructor does not initialize the final variable:
class TestABC {
final var _name : String // INVALID CODE, ALL CONSTRUCTORS MUST INITIALIZE _name IN ALL CODE PATHS.
construct() { // does not initialize the variable
}
construct(b : boolean){
_name = "there"
}
}
