/ Java  

Java final and static keyword

Final keyword

According to the context of the program, the Java keyword final has the meaning of “this cannot be changed” or “end state”, which can be used for non-abstract classes, non-abstract class member methods and variables. You may need to prevent change for two reasons: design or efficiency.

  • Final class cannot be inherited and has no subclasses. The methods in the final class are final by default.
  • Final methods cannot be overridden by subclass methods, but can be inherited.
  • Final member variable represents a constant and can only be assigned once, and the value will not change after the assignment.
  • Final cannot be used to the construction method.

Note: The private member methods of the parent class cannot be overridden by subclass methods, so private type methods are final by default.

In general, final is used to declare attributes, methods, and classes, respectively, indicating that attributes are immutable, methods cannot be overridden, and classes cannot be inherited.

Apply final to a class

When a class is modified with final, it indicates that this class cannot be inherited. The member methods of the final class have no chance to be overwritten, so the default is final. That means this class is a leaf class in the inheritance tree, and the design of this class has been considered perfect without modification or expansion. For member variabbles of the final class, you can define it as final or not final. As for the method, it naturally becomes final. When using final to modify a class, you should choose carefully, unless this class will not be used for inheritance in the future or for safety reasons, try not to design the class as a final class.

The class that most often modified with final is the utility class. There are a lot of utility classes used in Java projects, such as JDK’s own utility class java.lang.Math, java.util.Collections, etc. The methods and properties of the utility class are static and can be accessed without generating an instance. The utility class has been well designed and does not need to be inherited. Since it does not want to be initialized or inherited, JDK has dealt with this. Let’s take a look at the code of java.lang.Math:

1
2
3
4
5
6
7
8
9
public final class Math {   
    private  Math() { }  
    public static final double E = 2.7182818284590452354;
    public static final double PI = 3.14159265358979323846;

    public static double sin(double a ) 
        return StrictMath.sin(a);
    }   
}

Apply final to a method

There are two reasons for using the final method:

  1. To show that the functions provided by this method have met the requirements, do not need to be extended, and do not allow any subclasses that inherit from this class to override this method, but the inherited class can still use this method directly.
  2. Efficiency. When the compiler encounters the call to the final method, it will convert all calls to this method into an inline call mechanism, greatly improving execution efficiency. However, when the method body is very large, or when the method is called in multiple places, the calling code will quickly expand, which may affect efficiency, so final should be used to define the method with caution. Only set the method to final if you want to explicitly prohibit the method from being overridden in subclasses.

Note: The private method of the class will be implicitly designated as the final method.

Apply final to a variable

Dinal is used the most to modify variables . For a final variable, if the variable is of primitive data type, its value cannot be changed once it is initialized; if it is a variable of reference type, it cannot point to another object after it is initialized.

The initialization of variables can be in two places, one is its definition, and the other is in the constructor.

There are three types of final modified variables: static variables, instance variables and local variables, which represent three types of constants. When the final variable is defined, you can declare it first without giving an initial value. This variable is also called final blank. In any case, the compiler ensures that the blank final must be initialized before use. With this guarantee, the final data member can be implemented differently according to the object, but has the characteristics of keeping it constant.

Another usage is to define the parameters in the method as final. For basic type variables, this has no practical meaning, because the basic type variables are passed by value when calling the method. When you change this parameter variable in the method, the formal parameters are changed, and the actual parameters are not affected. However, it is very practical for object variables, because object variables are passed by reference. Your modification of the object variable in the method will also affect the actual parameter object. When you restrict the object variable that cannot be changed as a parameter in the method, be sure to explicitly use final to declare it.

Static keyword

Static means “global” or “static”, used to modify member variables and member methods, and can also form static code blocks, but there is no concept of global variables in the Java language.

Member variables and member methods modified by static are independent of any objects of this class. In other words, it does not depend on a specific instance of the class and is shared by all instances of the class. As long as the class is loaded, the Java virtual machine can find them in the method area of the runtime data area based on the class name. Therefore, the static object can be accessed before any object of the class to which it belongs is created without reference to any object. There are three types of static members in a class: static member variables, static methods, and static code blocks. They all have the following characteristics:

  • When the class is loaded, create and initialize or execute code;
  • They have only one copy for a class;
  • All instances of the class can access them.

Static member variable: it will be created and initialized after the class is loaded. Because of its uniqueness, it is usually used for the data record of the object, for example, reference storage in singleton mode.

Static method: it can be accessed by the object or directly by the class name.

Static code block: which is decorated with static code surrounded by curly brackets “{…}”. These codes can use static member variables and methods, which are also called when the class is loaded.

Static variables

There are two types of member variables according to whether they are static: one is a variable modified by static, called static variable or class variable; the other is a variable that is not modified by static, called instance variable. The difference between the two is that for static variables, they have only one copy in memory (saving memory), the JVM only allocates memory for statics once, and completes the memory allocation of static variables during the class loading process, which can be accessed directly by the class name (convenient), Of course it can also be accessed through objects (but this is not recommended). For instance variables, if an instance is created, the instance variable will be allocated once, and the instance variable can have multiple copies in memory without affecting each other (flexible).

Static method

Static methods can be called directly by the class name, any instance can be called, so the static method can not use this and super keywords, can not directly access the instance variables and instance methods of the class (that is, non-static member variables and members method). Static methods can only access the static member variables and static member methods of the class because instance members are associated with specific objects.

Because the static method is independent of any instance, the static method must be implemented. It can not be an abstract abstract.

Static code block

The static code block is a static statement block in the class that is independent of the class members. There can be more than one, and the position can be placed anywhere. It is not in any method body. These static code blocks will be executed when the JVM loads the class. If there are multiple static code blocks, the JVM will execute them in the order in which they appear in the class, and each code block will only be executed once.

See details about static code block: Java Static code block.

What does putting static and final together mean

When static and final modifies member variables or member methods together, it can be simply understood as a “global constant”!

For variables, it means that once a value is given, it cannot be modified, and can be accessed by the class name, the variable is shared by all instances of the class.

For methods, it means that they cannot be overridden and can be accessed directly by the class name. In particular, pay attention to a problem: for instance constants modified by static and final, the instance itself cannot be changed, but for instance variables of some container types (for example, ArrayList, HashMap), the container variable itself cannot be changed, but it can be modified. Objects stored in containers are used a lot in programming.