Take you to analyze java final keywords in three minutes

This article mainly introduces the use of java final keyword to help everyone better understand and use Java. Interested friends can understand that
the meaning of the Java keyword final is slightly different according to the context, but usually it refers to The answer is "This cannot be changed". There are two reasons to prevent change: design or efficiency. Because these two reasons are far apart, it is possible to misuse the keyword final.

The following sections discuss three possible uses of final: data, methods, and classes.
1) Final data
For the case of compile-time constants, the compiler can bring the constants into the calculation, which can reduce some runtime burdens. In Java, such constants must be basic types and are modified with the keyword final. You must assign values ​​when defining constants .

Final static basic variables with constant initial values ​​(ie, compile-time constants) are named in all uppercase, and words are separated by underscores.

An attribute modified by both static and final will only occupy a section of storage space that cannot be changed .

When using final to decorate object references instead of basic types,

  • For basic types, final keeps the value constant.
  • For object references, final makes the reference constant.
    Once the reference is initialized to point to an object, it cannot be changed to point to other objects. However, the object itself can be modified, and Java does not provide a method to set any object as a constant. (You can write your own class to achieve the effect of making the object constant) This restriction also applies to arrays, which are also objects.
    Example:
import java.util.*;
 
class Value {
    
    
  int i;
  Value(int i) {
    
    
    this.i = i;
  }
}
 
/**
 * @author Limh
 */
public class FinalData {
    
    
  private static Random rand = new Random(47);
  private String id;
 
  public FinalData(String id) {
    
    
    this.id = id;
  }
  private final int valueOne = 9;
  private static final int VALUE_TWO = 99;
  public static final int VALUE_THREE = 39;
  private final int i4 = rand.nextInt(20);
  static final int INT_5 = rand.nextInt(20);
  private Value v1 = new Value(11);
  private final Value v2 = new Value(22);
  private static final Value VAL_3 = new Value(33);
  private final int[] a = {
    
    1, 2, 3, 4, 5, 6};
 
  @Override
  public String toString() {
    
    
    return id + ": " + "i4 = " + i4 + ", INT_5 = " + INT_5;
  }
 
  public static void main(String[] args) {
    
    
    FinalData fd1 = new FinalData("fd1");
    //v2=new Value(22);
    fd1.v2.i++;
    fd1.v1 = new Value(9);
    //a.length = 6
    for (int i = 0; i < fd1.a.length; i++) {
    
    
      fd1.a[i]++;
    }
    System.out.println(fd1);
    System.out.println("Creating new FinalData");
    FinalData fd2 = new FinalData("fd2");
    System.out.println(fd1);
    System.out.println(fd2);
  }
}

Output:

fd1: i4 = 15, INT_5 = 18
Creating new FinalData
fd1: i4 = 15, INT_5 = 18
fd2: i4 = 13, INT_5 = 18

Because the first variable and the second variable are final basic types with compile-time values, they can both be used as compile-time constants without much difference. The third variable is a more typical way of defining constants: public means that it can be accessed outside the package, static emphasizes that there is only one, and final means that it is a constant.

As you can see in main(), v2 is final does not mean that you cannot modify its value. Because it is a reference, it just means that it cannot point to a new object.

2) Blank final
Blank final refers to the final attribute without initial value.

The compiler ensures that the blank final must be initialized before use. In this way, the final attribute value of each object of a class can be different, and it can also maintain its immutability .

You must perform the assignment of final variables at the time of definition or in each constructor. This ensures that the final attribute has been initialized before use.

3) Final parameter
In the parameter list, declaring the parameter as final means that the object or basic variable pointed to by the parameter cannot be changed in the method:

class Gizmo {
    
    
  public void spin() {
    
    
 
  }
}
 
/**
 * @author Limh
 */
public class FinalArguments {
    
    
  void with(final Gizmo g) {
    
    
    //-g = new Gizmo(); 
    // Illegal -- g is final
  }
 
  void without(Gizmo g) {
    
    
    g = new Gizmo(); // OK -- g is not final
    g.spin();
  }
 
  //void f(final int i) { i++; } // Can't change
  // You can only read from a final primitive
  int g(final int i) {
    
    
    return i + 1;
  }
 
  public static void main(String[] args) {
    
    
    FinalArguments bf = new FinalArguments();
    bf.without(null);
    bf.with(null);
  }
}

4) There are two reasons why final methods
use final methods.

Lock the method to prevent subclasses from changing the method by overwriting. This is for inheritance considerations to ensure that the behavior of the method will not change due to inheritance.
Use final only to explicitly prohibit overwriting methods.

5)
All private methods in final and private classes are implicitly designated as final. Because the private method cannot be accessed, it cannot be overridden.

6) Final class
When a class is said to be final (the final keyword is before the class definition), it means that it cannot be inherited. The reason for this is because the design of the class never needs to be changed, or because it is not expected to have subclasses for safety reasons.

Since the final class prohibits inheritance, all methods in the class are implicitly designated as final, so there is no way to override them. You can add final modifiers to the methods in the final class, but it will not add any meaning.

The above is the detailed content of the comprehensive analysis of java final keywords. For more information about java final keywords, please pay attention to other related articles in the editor!

Guess you like

Origin blog.csdn.net/dcj19980805/article/details/115329043