final Instance Variables

The principle of least privilege is fundamental to good software engineering. In the context of an application, the principle states that code should be granted only the amount of privilege and access that the code needs to accomplish its designated task, but no more. Let us see how this principle applies to instance variables.

Some instance variables need to be modifiable and some do not. You can use the keyword final to specify that a variable is not modifiable (i.e., it is a constant) and that any attempt to modify it is an error. For example,

 private final int INCREMENT;

declares a final (constant) instance variable INCREMENT of type int. Although constants can be initialized when they are declared, this is not required. Constants can be initialized by each of the class's constructors.

Software Engineering Observation 8.13

Declaring an instance variable as final helps enforce the principle of least privilege. If an instance variable should not be modified, declare it to be final to prevent modification.

Our next example contains two classesclass Increment (Fig. 8.15) and class IncrementTest (Fig. 8.16). Class Increment contains a final instance variable of type int named INCREMENT (Fig. 8.15, line 7). Note that the final variable is not initialized in its declaration, so it must be initialized by the class's constructor (lines 913). If the class provided multiple constructors, every constructor would be required to initialize the final variable. The constructor receives int parameter incrementValue and assigns its value to INCREMENT (line 12). A final variable cannot be modified by assignment after it is initialized. Application class IncrementTest creates an object of class Increment (Fig. 8.16, line 8) and provides as the argument to the constructor the value 5 to be assigned to the constant INCREMENT.

Figure 8.15. final instance variable in a class.

(This item is displayed on pages 386 - 387 in the print version)

 1 // Fig. 8.15:
 2 // final instance variable in a class.
 4 public class Increment
 5 {
 6 private int total = 0; // total of all increments
 7 private final int INCREMENT; // constant variable (uninitialized)
 9 // constructor initializes final instance variable INCREMENT 
10 public Increment( int incrementValue ) 
11 { 
12  INCREMENT = incrementValue; // initialize constant variable (once)
13 } // end Increment constructor 
15 // add INCREMENT to total
16 public void addIncrementToTotal()
17 {
18 total += INCREMENT;
19 } // end method addIncrementToTotal
21 // return String representation of an Increment object's data
22 public String toString()
23 {
24 return String.format( "total = %d", total );
25 } // end method toIncrementString
26 } // end class Increment

Figure 8.16. final variable initialized with a constructor argument.

 1 // Fig. 8.16:
 2 // final variable initialized with a constructor argument.
 4 public class IncrementTest
 5 {
 6 public static void main( String args[] )
 7 {
 8 Increment value = new Increment( 5 );
10 System.out.printf( "Before incrementing: %s

", value );
12 for ( int i = 1; i <= 3; i++ )
13 {
14 value.addIncrementToTotal();
15 System.out.printf( "After increment %d: %s
", i, value );
16 } // end for
17 } // end main
18 } // end class IncrementTest
Before incrementing: total = 0

After increment 1: total = 5
After increment 2: total = 10
After increment 3: total = 15

Common Programming Error 8.10

Attempting to modify a final instance variable after it is initialized is a compilation error.

Error-Prevention Tip 8.2

Attempts to modify a final instance variable are caught at compilation time rather than causing execution-time errors. It is always preferable to get bugs out at compilation time, if possible, rather than allow them to slip through to execution time (where studies have found that the cost of repair is often many times more expensive).

Software Engineering Observation 8.14

A final field should also be declared static if it is initialized in its declaration. Once a final field is initialized in its declaration, its value can never change. Therefore, it is not necessary to have a separate copy of the field for every object of the class. Making the field static enables all objects of the class to share the final field.

If a final variable is not initialized, a compilation error occurs. To demonstrate this, we placed line 12 of Fig. 8.15 in a comment and recompiled the class. Fig. 8.17 shows the error message produced by the compiler.

Figure 8.17. final variable INCREMENT must be initialized. variable INCREMENT might not have been initialized
 } // end Increment constructor
1 error

Common Programming Error 8.11

Not initializing a final instance variable in its declaration or in every constructor of the class yields a compilation error indicating that the variable might not have been initialized. The same error occurs if the class initializes the variable in some, but not all, of the class's constructors.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look


Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams


Searching and Sorting

Data Structures



Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2



Accessing Databases with JDBC


JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover

show all menu

Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615
Similar book on Amazon © 2008-2017.
If you may any questions please contact us: