Details the use of the final keyword in Java

  • 2020-04-01 04:05:12
  • OfStack

The final meaning

Final is a reserved keyword in Java that allows you to declare member variables, methods, and classes. Once you declare the reference as final, you cannot change the reference. The compiler checks the code, and if you try to initialize the variable again, the compiler will report a compilation error.
The final variable

Anything that is declared final to a member variable or a local variable (called a local variable ina method or ina code block) is called a final variable. Here is an example of a final modifier:


final int constValue = 1;
// constValue = 2; The final local variable constValue cannot be assigned.

Added a point:

      Final member variables must be initialized at declaration time or in the constructor, otherwise the compiler will report an error.       You cannot assign a value to a final variable again.       All variables in an anonymous class must be final.

The final method

Final can also declare methods. The final keyword in front of the method name means that the method cannot be subclassed. You can declare a method as final if you think it's fully functional enough that you don't need to change it ina subclass.
Final-declared methods are faster than non-final methods because they are statically bound at compile time and do not need to be dynamically bound at run time. Here is an example of the final method:


public class Person
{
  public final void printName() {
    System.out.println("wangzhengyi");
  }
}


Final class

Classes that are decorated with final are called final classes. Final classes are usually fully functional and cannot be inherited. Many classes in Java are final, such as the String class.

One of the nice things about an immutable class is that it's thread-safe, and you don't have to worry about thread-safety in a multithreaded environment. To create an immutable class, follow these steps:

      Declare the class final so that it cannot be inherited.       Declare all members private so that direct access to them is not allowed.       Do not provide setter methods for variables.       Declare all mutable members final so that they can only be assigned once.       Deep copy is done by initializing all members with the constructor.       In getter methods, instead of returning the object itself directly, clone the object and return a copy of the object.

      Note: difference between shallow and deep copy:

              Shallow copy (shallow clone) : all variables of the copied object have the same values as the original object, and all references to other objects still refer to the original object. In other words, only the primitive type of the object is copied, and the object type still belongs to the original reference.
              Deep copy (deep clone) : all copied variables have the same values as the original object, except for those that reference other objects. Variables that reference other objects will point to new objects that have been copied, instead of the old ones. In other words, you not only copy the basic type of the object, but also the object within the original object.

Examples of immutable classes:


import java.util.HashMap;
import java.util.Iterator;


public class FinalClassExample {
  private final int id;

  private final String name;

  private final HashMap<Integer, String> hMap;

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  
  public HashMap<Integer, String> gethMap() {
    return (HashMap<Integer, String>)hMap.clone();
  }

  
  public FinalClassExample(int id, String name, HashMap<Integer, String> map) {
    this.id = id;
    this.name = name;

    HashMap<Integer, String> tMap = new HashMap<Integer, String>();
    int key;
    Iterator<Integer> iterator = map.keySet().iterator();
    while (iterator.hasNext()) {
      key = iterator.next();
      tMap.put(key, map.get(key));
    }

    this.hMap = tMap;
  }

  
  
}

Final keyword benefits

The advantages of using the final keyword are as follows:

      The final keyword improves performance. Both the JVM and Java applications cache final variables.       Final variables can be safely Shared ina multithreaded environment without additional synchronization overhead.       With the final keyword, the JVM optimizes methods, variables, and classes.


Related articles: