Summary of the use of Java keywords final and static

Summary of the use of Java keywords final and static

1. final
        According to the program context, the Java keyword final has the meaning of "this cannot be changed" or "final state", which can modify non-abstract classes, non-abstract class member methods and variables . You may need to block change for two reasons: design or efficiency.
        A final class cannot be inherited, there is no subclass, and methods in a final class 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, and the value will not change after assignment.
        final cannot be used to decorate constructors.
        Note: The private member method of the parent class cannot be overridden by the subclass method, so the method of the private type is of the final type by default.

1. Final classes
        Final classes cannot be inherited, so the member methods of final classes have no chance to be overridden, and are final by default. When designing a class, if the class does not need to have 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 a final class.
2. Final method
        If a class does not allow its subclasses to override a method, the method can be declared as final.
        There are two reasons to use final methods:
        first, to lock the method, preventing any inherited class from modifying its meaning and implementation.
        Second, efficient. When the compiler encounters a final method call, it will switch to the inline mechanism, which greatly improves the execution efficiency.
        E.g:
public class Test1 {
public static void main(String[] args) {
    // TODO automatically generates method stubs
}
public void f1() {
    System.out.println("f1");
}
//Methods that cannot be overridden by subclasses
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 parent class method f1 is overridden!");
}
public static void main(String[] args) {
    Test2 t= new Test2();
    t.f1();   
    t.f2(); //Call the final method inherited from the parent class
    t.f3(); //Call the method inherited from the parent class
    //t.f4(); //The call fails and cannot be obtained from the parent class Inheritance to obtain
}
}
3. Final variables (constants)
        are represented by final-modified member variables, and once the value is given, it cannot be changed!
        There are three types of variables modified by final: static variables, instance variables and local variables, which represent three types of constants respectively.
        As you can see from the following example, once a final variable is given an initial value, the value cannot be changed.
        In addition, when a final variable is defined, it can be declared first without giving an initial value. The variable is also called final blank. In any case, the compiler ensures that blank final must be initialized before use. However, final whitespace provides more flexibility in the use of the final keyword final, so that final data members in a class can be implemented differently depending on the object, but have the characteristic of keeping them constant.

package org.leizhimin;

public class Test3 {
        private final String S = "final instance variable 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; //final blank, the initial value must be assigned when the object is initialized

        public Test3(int x) {
                E = x;
        }

        /**
         * @param args
         */
        public static void main(String[] args) {
                Test3 t = new Test3(2);
                //tA=101; //Error, the value of final variable cannot be changed once given
                //tB=91; //Error, final variable Once given, the value cannot be changed
                //tC=81; //Error, the value of final variable cannot be changed once given
                //tD=71; //Error, the value of final variable cannot be changed once given

                System. out.println(tA);
                System.out.println(tB);
                System.out.println(tC); //It is not recommended to access static fields in object mode
                System.out.println(tD); //It is not recommended to access static fields in object mode
                System.out.println(Test3.C);
                System .out.println(Test3.D);
                //System.out.println(Test3.E); //Error, because E is final blank, which varies according to different object values.
                System.out.println(tE);

                Test3 t1 = new Test3(3);
                System.out.println(t1.E); //final blank variable E varies according to the object
        }

        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, assign when needed
                final int b = 4; //local constants --final is used for local variables
                final int c; //final blank, always No assignment.   
                a = 3;
                //a=4; Error, already assigned value.
                //b=2; Error, assigned value.
        }
}

4. Final parameter
        When the function parameter is final type , you can read and use this parameter, but you cannot change the value of this parameter.

public class Test4 {
        public static void main(String[] args) {
                new Test4().f1(2);
        }

        public void f1(final int i) {
                //i++; //i is of final type, value is not allowed changed.System.out.print
                (i);
        }
}

Second, static

        static means "global" or "static", which is used to modify member variables and member methods, and can also form static 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 the class. That is, it does not depend on a class-specific instance and is shared by all instances of the class. As long as the class is loaded, the Java virtual machine can locate them 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 referencing any objects.

        The static member variables and member methods modified with public are essentially global variables and global methods. When the object of its class is declared, a copy of the static variable is not generated, but all instances of the class share the same static variable.

        A static variable can be modified with private, which means that the variable can be used in the static code block of the class, or in other static member methods of the class (of course, it can also be used in non-static member methods - nonsense), but it cannot be used in other classes. It is important to refer directly by the class name. In fact, you need to understand that private is the access limit, and static means that it can be used without instantiation, which is much easier to understand. The effect of adding other access permission keywords in front of static is similar.

        Statically modified member variables and member methods are conventionally called static variables and static methods, which can be accessed directly through the class name. The access syntax is:
class name. static method name (parameter list...)
class name. static variable name
        use A code block decorated with static means a static code block, which is executed when the Java Virtual Machine (JVM) loads the class (very useful, huh, huh).

1. Static variables
        can be classified into two types according to whether they are static or not: 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:
        for static variables, there is only one copy in memory (saving memory), JVM allocates memory for static only once, and completes memory allocation for static variables during the process of loading classes, 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 not created, memory will be allocated for the instance variable once. Instance variables can have multiple copies in memory without affecting each other (flexible).

2. Static methods
        Static methods can be called directly through the class name, and any instance can also be called. Therefore, the keywords this and super cannot be used in static methods, and instance variables and instance methods of the class to which they belong cannot be directly accessed (that is, those without static). member variables and member member methods), can only access static member variables and member methods of the class to which they belong. Because instance members are associated with a specific object! This needs to be understood, to understand the truth, not memory! ! !
        Because static methods are independent of any instance, static methods must be implemented, not abstract.

3. Static code block
        Static code block is also called static code block. It is a static statement block in a class that is independent of class members. There can be multiple, and the location can be placed anywhere. It is not in any method body. It will be executed when the JVM loads the class. These static code blocks, 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. 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 自动生成方法存根
        }

        static {
                Test5.a = 5;
                System.out.println(a);
        }

        public void f() {
                System.out.println("hhahhahah");
        }
}

Operation result:
3
hhahhahah
1000
4
5
        Some static variables can be assigned values ​​using static code blocks, and finally look at these examples, they are all a static main method, so that the JVM is in the When running the main method, it can be called directly without creating an instance.

4. Static and final are used together to indicate what
        static final is used to modify member variables and member methods, which can be simply understood as "global constants"!
        For variables, it means that once a value is given, it cannot be modified and can be accessed through the class name.
        For methods, it means that it is not overridable and can be accessed directly by the class name.
      
        Pay special 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 (such as ArrayList, HashMap), the container variable itself cannot be changed, but it can be modified Objects stored in containers are used a lot in programming.
        Maybe after talking so much, it makes you dizzy, let's look at an example:

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<String> alStaticFinalVar = new ArrayList<String>();

        private void test() {
                System.out.println("-------------值处理前----------\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="Hahahaha"; //Error, final means final state, the variable itself cannot be changed.
                strStaticVar = "Hahahaha"; //Correct, static means Class variable, the value can be changed.
                //strFinalVar="Hehehehe"; //Error, final means the final state, the initial value (even if a null is given) is required when it is defined, and once it is given, it cannot be changed.
                //intStaticFinalVar=2; //Error, final means the final state, the initial value (even if a null is given) is required when it is defined, and once it is given, it cannot be changed.
                //integerStaticFinalVar=new Integer(8); //Error, final means the final state, the initial value (even if null) is required when it is defined, and once it is given, it cannot be changed.
                alStaticFinalVar.add("aaa"); //Correct, the container variable itself has not changed, but the storage content has changed. This rule is very common and has many uses.
                alStaticFinalVar.add("bbb"); //Correct, the container variable itself has not changed, but the storage content has changed. This rule is very common and has many uses.

                System.out.println("-------------after value 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("
                System.out.println("integerStaticFinalVar=" + integerStaticFinalVar + "\r\n");
                System.out.println("alStaticFinalVar=" + alStaticFinalVar + "\r\n");
        }

        public static void main(String args []) {
                new TestStaticFinal().test();
        }
}

The result is as follows:
-------------Before value processing----------
strStaticFinalVar=aaa
strStaticVar= null
strFinalVar=null
intStaticFinalVar=0
integerStaticFinalVar=8
alStaticFinalVar=[]
-------------After value processing----------
strStaticFinalVar=aaa
strStaticVar=hahahaha
strFinalVar=null
intStaticFinalVar=0
integerStaticFinalVar=8
alStaticFinalVar=[aaa, bbb]

Process finished with exit code 0

        After reading the above example, it becomes much clearer, but it must be understood that the object "installed" in the container type variable modified by static final can be changed . This is very different from general primitive types and class type variables.

-------------------------------------------------- --

static Object obj = new Object(), what is the difference between a static object and a non-static object

1.synchronized modifies a method or a code block to ensure that at most one thread executes the code at the same time. 2. Static variables that cannot be modified variables
are class-level variables, that is to say, all instances see the same static variable, and competition will occur when each instance accesses; non-static objects are instance variables, each Instances have their own variables and do not disturb each other
. 3. Four necessary conditions for deadlock: (1) Mutual exclusion condition: a resource can only be used by one process at a time. (2) Request and hold conditions: When a process is blocked due to requesting resources, it will hold on to the obtained resources. (3) No deprivation condition: The resources that the process has obtained cannot be forcibly deprived before the end of the use. (4) Circular waiting condition: A cyclic waiting resource relationship is formed between several processes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326181765&siteId=291194637