Final variable, final method, or final class
The use of the keyword final
and its effects depend on the context. It can make a variable value unchangeable, a method not overridable, or a class not extendable. We will briefly discuss each of this situations.
Final variable
If a keyword final
is placed in front of a variable declaration, the value of this variable once assigned (the variable is initialized) cannot be changed. The way a variable can be initialized depends on how the variable is used. There are three kinds of variable usage, and each has different initialization rules:
- A local variable is a variable declared in the block of code; it can be initialized using an assignment in the same statement with the declaration, or sometime later, but only once; here are some examples:
class SomeClass{ private String someValue = "Initial value"; public void setSomeValue(String someValue) { this.someValue = someValue; } public String getSomeValue() { return someValue; } ...