Java Programming/Keywords/final

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

final is a keyword.

It has more than one meaning depending whether it used for a class, a method, or for a variable.

  • It is denoting that a variable is to be constant. This is similar to const in other languages. A variable declared with the final keyword cannot be modified by the program after initialization. This is useful for universal constants, such as pi, or other values that the programmer would like to keep constant throughout the code.
  • It marks a method final, meaning that subclasses can not override this method. The compiler checks and gives an error if you try to override the method.
  • It marks a class final, meaning that the class can not be subclassed.

For Example

static final double PI = 3.1415926;

final public void method()
{
 ...
}

final public class MyClass
{
 ...
}

Note that final is always placed before the variable type in a constant, before the return type of a method, and before the keyword class in a class header.

See also: