Home | | Web Programming | Introducing final - Java

Chapter: Java The Complete Reference : The Java Language : A Closer Look at Methods and Classes

Introducing final - Java

A field can be declared as final. Doing so prevents its contents from being modified, making it, essentially, a constant.

Introducing final

 

A field can be declared as final. Doing so prevents its contents from being modified, making it, essentially, a constant. This means that you must initialize a final field when it is declared. You can do this in one of two ways: First, you can give it a value when it is declared. Second, you can assign it a value within a constructor. The first approach is the most common. Here is an example:

final int FILE_NEW = 1; 

final int FILE_OPEN = 2; 

final int FILE_SAVE = 3; 

final int FILE_SAVEAS = 4; 

final int FILE_QUIT = 5;

 

Subsequent parts of your program can now use FILE_OPEN, etc., as if they were constants, without fear that a value has been changed. It is a common coding convention to choose all uppercase identifiers for final fields, as this example shows.

In addition to fields, both method parameters and local variables can be declared final. Declaring a parameter final prevents it from being changed within the method. Declaring a local variable final prevents it from being assigned a value more than once.

The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to variables. This additional usage of final is described in the next chapter, when inheritance is described.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Language : A Closer Look at Methods and Classes : Introducing final - Java |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.