Article source: lavasoft.blog.51cto.com/62575/18771…

Java keyword final, static use summary

 

The Java keyword final can mean “this is immutable” or “final state” depending on the context of the program, and it can modify non-abstract classes, non-abstract class member methods, and variables. You may need to prevent change for two reasons: design or efficiency.

Final classes cannot be inherited, there are no subclasses, and methods in final classes are final by default. Final methods cannot be overridden by subclass methods, but can be inherited. Final member variables represent constants and can only be assigned once, after which the value does not change. Final cannot be used to modify constructors. Note: Private member methods of a parent class cannot be overridden by subclass methods, so methods of private type are final by default.

 

Final classes cannot be inherited, so the member methods of a final class have no chance of being overridden. They are all final by default. When designing a class, if the class does not need subclasses, the implementation details of the class are not allowed to change, and you are sure that the class will not be extended, then design it as final.

If a class does not allow subclasses to override a method, the method can be declared final. There are two reasons to use final methods: first, to lock the method and prevent any inherited classes from changing its meaning and implementation. Second, efficient. When a final method is called, the compiler will turn to the embedded mechanism, which greatly improves execution efficiency. For example: \

Public class Test1 {public static void main(String[] args) {public static void main(String[] args) {public void f1() {system.out.println ( “f1”); } public final void f2() {system.out.println (“f2”);} public final void f2() {system.out.println (“f2”); } public void f3() { System.out.println( “f3”); } private void f4() { System.out.println( “f4”); }} public class Test2 extends Test1 {public void f1(){system.out.println (“Test1 “); ); } public static void main(String[] args) { Test2 t= new Test2(); t.f1(); t.f2(); // Call the final method t.f3() inherited from the parent class; // call the method inherited from the parent class //t.f4(); // Call failed, cannot inherit from parent class}}

3, final variables (constants) use final modified member variables to represent constants, the value once given cannot be changed! Final modifies three types of variables: static variables, instance variables, and local variables, representing three types of constants. As you can see from the following example, once a final variable has been given an initial value, it cannot be changed. In addition, when a final variable is defined, it can be declared first without giving an initial value. This variable is also called final whitespace. In any case, the compiler ensures that blank final is initialized before it can be used. However, final whitespace provides greater flexibility in the use of the final keyword final, so that final data members ina class can be implemented to vary from object to object, yet have the property of remaining constant.

 

package org.leizhimin; Public class Test3 {private final String S = “final instance S”; private final int A = 100; public final int B = 90; public static final int C = 80; private static final int D = 70; public final int E; Public Test3(int x) {E = x; public Test3(int x) {E = x; } /** * @param args */ public static void main(String[] args) { Test3 t = new Test3(2); //t.A=101; // the final variable cannot be changed once given //t.B=91; // the final variable cannot be changed once given //t.C=81; // the final variable cannot be changed once given //t.D=71; // Error,final variable value once given cannot change system.out.println (t.A); System.out.println(t.B); System.out.println(t.C); // Using objects to access static fields system.out.println (t.D) is not recommended; // Object access to static fields system.out.println (test3.c) is not recommended; System.out.println(Test3.D); //System.out.println(Test3.E); // Error, because E is final blank, depending on the object value. System.out.println(t.E); Test3 t1 = new Test3(3); System.out.println(t1.E); Private void test() {system.out.println (new Test3(1).a); private void test() {system.out.println (new Test3(1).a); System.out.println(Test3.C); System.out.println(Test3.D); } public void test2() { final int a; //final blank, if necessary final int b = 4; // local constant –final for local variables final int c; //final is blank, and no value is assigned. //a=4; //b=2; Error, assigned value already.}}

 

When a function argument is final, you can read and use it, but you cannot change its value. \

 

public class Test4 { public static void main(String[] args) { new Test4().f1(2); } public void f1( final int i) { //i++; // I is final and cannot be changed. System.out.print(i); }}

Second, the static

Static means “global” or “static” and is used to modify member variables and methods. Static code blocks can also be formed, but the Java language does not have the concept of a global variable.

Member variables and member methods that are static are independent of any object of the class. That is, it does not depend on a class-specific instance and is shared by all instances of the class. As soon as the class is loaded, the Java virtual machine can find it in the method area of the runtime data area based on the class name. Therefore, a static object can be accessed before any of its objects are created, without reference to any objects.

When you declare a class object, you do not generate a copy of the static variable. Instead, all instances of the class share the same static variable.

 

A static variable can be preceded by a private modifier, indicating that the variable can be used in a static block of code or in other static member methods of the class (or in non-static member methods — duh), but not directly by the class name. This is important. In fact, you need to understand that private means access restricted, and static means don’t instantiate it, so it’s easier to understand. Static is similarly preceded by other access keywords.

 

Static variables and methods are conventionally called static variables and methods, and can be accessed directly by the class name. Static method name (parameter list…) Class name static variable name

A static modified block of code represents a static block of code that is executed when the Java Virtual Machine (JVM) loads a class (very useful, hehe).

 

Class member variables can be classified as static variables or class variables. Class member variables can be classified as static variables. The other type is a variable that is not modified static, called an instance variable. The difference is that there is only one copy of a static variable in memory (to save memory), and the JVM allocates memory only once for a static variable, which can be accessed directly (conveniently) by the class name, or by an object (but this is not recommended). For instance variables, memory is allocated once before an instance is created, and instance variables can have multiple copies in memory without affecting each other (flexible).

 

Static methods can be called directly from the class name, and any instance can be called. Therefore, static methods can not use this and super keywords, and cannot directly access the instance variables and methods of the class. Only static member variables and member methods of the owning class can be accessed. Because instance members are associated with specific objects! This needs to understand, want to understand the truth among them, not memory!! Because static methods are independent of any instance, static methods must be implemented and cannot be abstract.

 

A static code block is a static statement block that is independent of the class member. It is not inside any method. The JVM executes this static code block when loading a class. The JVM executes them in the order in which they appear in the class, and each code block is executed only once. For example: \

 

public class Test5 { private static int a; private int b; static { Test5.a = 3; System.out.println(a); Test5 t = new Test5(); t.f(); t.b = 1000; System.out.println(t.b); } static { Test5.a = 4; System.out.println(a); } public static void main(String[] args) {// TODO automatic generate method stubs} static {test5.a = 5; System.out.println(a); } public void f() { System.out.println( “hhahhahah”); }}

 

Run result: 3 hHAhhahah 1000 4 5

Static code blocks can be used to assign values to static variables. Finally, if you look at these examples, each of them has a static main method that the JVM can call directly when running the main method without creating an instance.

 

Static variables and methods are used to define static final variables and methods. For variables, the representation is not modifiable once given a value and is accessible by class name. For methods, the representation is not overridden and can be accessed directly by the class name.

       

One issue in particular should be noted:

For instance constants that are static or final, the instance itself cannot be changed, but for instance variables of some container types (e.g., ArrayList, HashMap), the variables themselves cannot be changed, but the objects stored in the container can be changed. This is often used in programming.

Let’s take a look at some examples:

 

public class TestStaticFinal { private static final String strStaticFinalVar = “aaa”; private static String strStaticVar = null; private final String strFinalVar = null; private static final int intStaticFinalVar = 0; private static final Integer integerStaticFinalVar = new Integer(8); private static final ArrayList

alStaticFinalVar = new ArrayList

(); Private void test () {System. Out. Println (” — — — — — — — — — — — — — value before processing — — — — — — — — — — \ r \ n “); System.out.println( “strStaticFinalVar=” + strStaticFinalVar + “\r\n”); System.out.println( “strStaticVar=” + strStaticVar + “\r\n”); System.out.println( “strFinalVar=” + strFinalVar + “\r\n”); System.out.println( “intStaticFinalVar=” + intStaticFinalVar + “\r\n”); System.out.println( “integerStaticFinalVar=” + integerStaticFinalVar + “\r\n”); System.out.println( “alStaticFinalVar=” + alStaticFinalVar + “\r\n”); //strStaticFinalVar=” ha ha ha ha “; // Error: final indicates the final state, and the variable itself cannot be changed. //strFinalVar=” static “; // Error: Final indicates the final state. The initial value is defined (even if null is given) and cannot be changed once given. //intStaticFinalVar=2; // Error: Final indicates the final state. The initial value is defined (even if null is given) and cannot be changed once given. //integerStaticFinalVar=new Integer(8); // Error: Final indicates the final state. The initial value is defined (even if null is given) and cannot be changed once given. alStaticFinalVar.add( “aaa”); // The container variable itself has not changed, but the contents of the container have changed. This rule is very common and has many uses. alStaticFinalVar.add( “bbb”); // The container variable itself has not changed, but the contents of the container have changed. This rule is very common and has many uses. System. The out. Println (” — — — — — — — — — — — — — value after processing — — — — — — — — — — \ r \ n “); System.out.println( “strStaticFinalVar=” + strStaticFinalVar + “\r\n”); System.out.println( “strStaticVar=” + strStaticVar + “\r\n”); System.out.println( “strFinalVar=” + strFinalVar + “\r\n”); System.out.println( “intStaticFinalVar=” + intStaticFinalVar + “\r\n”); System.out.println( “integerStaticFinalVar=” + integerStaticFinalVar + “\r\n”); System.out.println( “alStaticFinalVar=” + alStaticFinalVar + “\r\n”); } public static void main(String args[]) { new TestStaticFinal().test(); }}

 

The running results are as follows:

————- Value before processing ———-

strStaticFinalVar=aaa

strStaticVar=null

strFinalVar=null

intStaticFinalVar=0

integerStaticFinalVar=8

alStaticFinalVar=[]

————- after processing the value ———-

strStaticFinalVar=aaa

StrStaticVar = hahaha

strFinalVar=null

intStaticFinalVar=0

integerStaticFinalVar=8

alStaticFinalVar=[aaa, bbb]


Process finished with exit code 0

 

Looking at the example above, it’s a lot clearer, but it’s important to understand that objects “loaded” in container type variables decorated with static final are mutable. This is a big difference from ordinary primitives and class type variables.

\

\