Game Development Reference
In-Depth Information
Java's final Modifier: Variables, Methods, and Classes
That Cannot Be Modified
You have already explored the final modifier keyword as it is used to declare a con-
stant, along with a static keyword. A final data field variable can only be initialized
(set) one time. A final reference variable , which is a special type of Java variable that
contains a reference to an object in memory, cannot be changed (reassigned) to refer to
a different object; the data that are held inside the (final) referenced object can be
changed, however, as only the reference to the object itself is the final reference vari-
able, which is essentially locked in, using a Java final keyword.
A Java method can also be locked using the final modifier keyword. When a Java
method is made final, if the Java class that contains that method is subclassed, that final
method cannot be overridden , or modified, within the body of the subclass. This ba-
sically locks what is inside the method code structure. For example, if you want the
.start() method for your InvinciBagel class (were it ever to be subclassed) always to do
the same things that it does for your InvinciBagel superclass (prepare a JavaFX staging
environment), you use the following code:
public class InvinciBagel extends Application {
Button btn;
@Override
public final void start(Stage primaryStage) {
btn = new Button();
// The other method programming statements
continue here
}
}
This prevents any subclasses (public class InvinciBagelReturns extends InvinciBa-
gel) from changing anything regarding how the InvinciBagel game engine (JavaFX) is
set up initially, which is what the .start() method does for your game application (see
Chapter 4 ) . A class that is declared using a final modifier keyword cannot be extended,
or subclassed, locking that class for future use.
Search WWH ::




Custom Search