F.11. final Instance Variables

The principle of least privilege is fundamental to good software engineering. In the context of an application, it states that code should be granted only the amount of privilege and access that it needs to accomplish its designated task, but no more. This makes your programs more robust by preventing code from accidentally (or maliciously) modifying variable values and calling methods that should not be accessible.

Let’s see how this principle applies to instance variables. Some of them 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’s 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. Such variables can be initialized when they’re declared. If they are not, they must be initialized in every constructor of the class. Initializing constants in constructors enables each object of the class to have a different value for the constant. If a final variable is not initialized in its declaration or in every constructor, a compilation error occurs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset