How to use the final keyword in Java?


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

1) Direct assignment when declaring variables;

2) Non static member variables are assigned in the {} block, and static member variables are assigned in the static {} block;

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

Final modifier class

The final class cannot be inherited, so there will be no subclasses. The methods in the final class are final whether they are modified or not.

A simple final class is defined below:

  public final class FinalClass { }

//The following class inheritance will cause compilation errors

  class Sub extends FinalClass { }

Final modification method

Final method cannot be overridden. If in the parent classgameIf the method is final, the subclass cannot override the method, but can call the method (the final method of the parent class).

The following program attempts to rewrite the http://www.cungun.comfinal method of the game, which will cause a compilation error:

  public class FinalMethod {
  public final void say () { }


  class Sub extends FinalMethod {
/ / compilation errors will occur in the following methods

  public void say () { }


Final member variable

The variable modified by final cannot be changed, which means that it cannot be re assigned. Because the final modified member variable cannot be re assigned, the Java language stipulates that the final modified member variable must be the specified initial value displayed by the programmer.

The initial values specified by class variables and instance variables modified by final are as follows:

1) Class variable: you must specify the initial value in the static initialization block or when declaring this class variable, and you can only specify one of them.

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

Final modifies the difference between basic type variables and reference type variables:

When final modifies a basic type variable, the basic type variable cannot be changed. However, for a reference type variable, what it saves is only a reference. Final only ensures that the address referenced by the reference type variable will not change, that is, it always references the same object, but the object can be changed.