Wednesday, November 21, 2012

Java "final" modification

In the Java programming language, the final keyword is used in several different contexts to define an entity which cannot later be changed (or reassigned).

Final classes
A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.

Final methods
A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

Final variables
A final variable can only be initialized once, either via an initializer or an assignment statement. A final variable usually is initialized in its declaration. When the declaration is skipped, the variable is named "blank final" and there are rules where it have to be initialized. 

Final non-static variable:
A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared;

Final static variable:
Similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared;

Examples:

static final JButton button = new JButton();

or

static final JButton button;

static {
  button = new JButton();
}


Attention:
Finality doesn't guarantee immutability. For example:

public final Position pos;


This means:
pos= new Position( 3, 4 ); // this is illegal, reassigning is not allowed
pos.setX( 3 ); // legal
pos.serY( 4 ); // legal

No comments:

Post a Comment