Final variables can only be assigned once. There are three ways to assign values:

1) Assign values directly when declaring variables;

2) Non-static member variables are assigned in {} blocks; static member variables are assigned in static{} blocks;

3) Non-static member variables are assigned in the constructor.

Final modifier class

Final classes cannot be inherited, so there are no subclasses. A method ina final class is final with or without a final modification.

Here is a simple final class defined:

public final class FinalClass { }

// The following class inheritance will result in a compilation error

class Sub extends FinalClass { }

Final modification method

Final methods cannot be overridden. If the game method in the parent class is final, the child class cannot override the method, but it can call the method (the final method of the parent class).

The following program attempts to override the game’s http:// www.cungun.comfinal method and will cause a compilation error:

Public class finalMethod {public final void say () {}

}

Class Sub extends FinalMethod {// This method has a compiler error

public void say () { }

}

Final member variable

Final modifies a variable that cannot be changed, meaning that it cannot be reassigned. Since the member variable of the final modifier cannot be reassigned, the Java language dictates that the member variable of the final modifier must have the specified initial value displayed by the programmer.

The final modifier’s class and instance variables specify the initial value as follows:

1) Class variable: The initial value must be specified in the static initialization block or when declaring the class variable, and can only be specified in one of the two.

2) Instance variable: The initial value must be specified in the non-static initializer block, the declaration of the instance variable, or the constructor, and can only be specified in one of three.

Final modifies the difference between a variable of a primitive type and a variable of a reference type:

When final modifies a primitive type variable, a primitive type variable cannot be changed. However, for a variable of reference type, what it stores is only the reference. Final only guarantees that the address referenced by the variable of reference type will not change, that is, the same object is always referenced, but the object can be completely changed.