Use of the Java keyword static and final

Source: Internet
Author: User

Static

When declaring properties, methods in Java, you can use the keyword static to decorate.

1.static variables

There are two ways to classify a class member variable statically: A variable that is statically modified, called a static variable or a class variable, and another variable that is not modified by static, called an instance variable. The difference is that there is only one copy of the static variable in memory (memory saving), the JVM allocates only one memory at a time, completes the memory allocation of the static variable during the loading of the class, can be accessed directly (conveniently) by the class name, and, of course, is accessible through the object (but this is not recommended). For instance variables, when an instance is not created, the instance variable is allocated one memory, and the instance variable can have multiple copies in memory without compromising (flexibility).

2. Static code block
The static code block is automatically executed when the class is loaded. If there are multiple static blocks of code, the JVM executes them sequentially in the order in which they appear in the class, and each code block is executed only once.

3. Static method
The static method can be called directly from the class name, and any instance can also be called, so the static method cannot use the This and Super keywords, and cannot directly access the instance variables and instance methods of the owning class (that is, member variables and member methods without static). Only static member variables and member methods of the owning class can be accessed. Because the static method is independent of any instance, the static method must be implemented, not abstract.
The static method can only access static variables and methods, because non-static variables and methods are required to create an object to access, and static variables/methods do not need to create any objects.

********
Static data or methods that belong to the entire class and not to an object are not associated with any object instances of the class. Therefore, there can be a static method name between the subclass and the parent class with the same name, which does not involve overloading. Therefore, you cannot declare a variable in any method body as static, for example:

1 Fun () {2    Static int // illegal.  3 }

In fact, understand that static is only a storage place, and use the direct use, do not need to create objects, you can understand the above considerations.

In addition, in general, the class is not static, only the inner class can be added static to represent the nested class.

Final
When declaring properties, methods, and classes in Java, you can use the keyword final to decorate.
The final variable is a constant and can only be assigned once;
The final method cannot be overridden by a quilt class;
The final class cannot be inherited.

1. Final variable
Declaring a final field helps the optimizer make better optimization decisions, because if the compiler knows that the value of the field does not change, it can safely cache the value in the register. The final field also provides an additional level of security by having the compiler force the field to be read-only.
Its initialization can be in two places, one is its definition, that is, when the final variable is defined directly assigned to it, and the second is in the constructor. These two places can only be selected, either in the definition of the value, or in the constructor to give a value, not both in the definition of the value, but also in the constructor to give another value.
Once initialized, the immutable meaning is immutable for the base type, and its reference to the object variable cannot be changed.
When the function parameter is the final type, you can read it using the parameter, but you cannot change the value of the parameter.
In addition, when an inner class in a method is used with a parameter variable in a method, this parameter must also be declared final for use.
In Java, the normal variable system is automatically initialized, the numeric variable is automatically initialized to 0, and the remaining type variables are automatically initialized to null. However, a variable of the final type must show initialization, and the method of initialization must be assigned directly at the time of declaration or in the constructor method, and cannot be assigned by calling the function.

2. Final method
If a class does not allow its subclasses to overwrite a method, you can declare this method as the final method.
There are two reasons for using the final method:
First, lock the method to prevent any inherited classes from modifying its meaning and implementation.
Second, efficient. When the compiler encounters a call to the final method, it moves into the inline inline mechanism, which greatly improves execution efficiency.

Note that all private methods in a class are implicitly final. Because the private method cannot be taken, it cannot be overloaded.

3. Final class
The final class cannot be inherited, so the member methods of the final class have no chance of being overwritten, and the default is final. In the design class, if the class does not need to have subclasses, the implementation details of the class are not allowed to change, and it is certain that the class will not be extended, then it is designed as the final class.

-----------------
One particular issue to note:
For instance constants that are static and final modified, the instance itself can no longer be changed, but for some instance variables of the container type (for example, ArrayList, HashMap), the container variable itself cannot be changed, but the object stored in the container can be modified, which is a lot of programming.

Look at an example:

1 Importjava.util.ArrayList;2 3  Public classteststaticfinal {4         Private Static FinalString Strstaticfinalvar = "AAA";5         Private StaticString Strstaticvar =NULL;6         Private FinalString Strfinalvar =NULL;7         Private Static Final intIntstaticfinalvar = 0;8         Private Static FinalInteger Integerstaticfinalvar =NewInteger (8);9         Private Static FinalArraylist<string> Alstaticfinalvar =NewArraylist<string>();Ten  One         Private voidTest () { ASystem.out.println ("----------before-------------value processing"); -System.out.println ("strstaticfinalvar=" + Strstaticfinalvar + ""); -System.out.println ("strstaticvar=" + Strstaticvar + ""); theSystem.out.println ("strfinalvar=" + Strfinalvar + ""); -System.out.println ("intstaticfinalvar=" + Intstaticfinalvar + ""); -System.out.println ("integerstaticfinalvar=" + Integerstaticfinalvar + ""); -System.out.println ("alstaticfinalvar=" + Alstaticfinalvar + ""); +  -  +                 //strstaticfinalvar= "haha haha";//error, final indicates an end state, and the variable itself cannot be changed. AStrstaticvar = "haha haha";//correct, static represents a class variable, and the value can be changed. at                 //strfinalvar= "hehe hehe"; //Error, final represents the final state, the initial value (even if given a null) at the time of definition, and cannot be changed once given.  -                 //intstaticfinalvar=2; //Error, final represents the final state, the initial value (even if given a null) at the time of definition, and cannot be changed once given.  -                 //integerstaticfinalvar=new Integer (8); //Error, final represents the final state, the initial value (even if given a null) at the time of definition, and cannot be changed once given.  -Alstaticfinalvar.add ("AAA");//correctly, 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");//correctly, the container variable itself has not changed, but the storage content has changed. This rule is very common and has many uses.  -  inSystem.out.println ("----------after-------------value processing"); -System.out.println ("strstaticfinalvar=" + Strstaticfinalvar + ""); toSystem.out.println ("strstaticvar=" + Strstaticvar + ""); +System.out.println ("strfinalvar=" + Strfinalvar + ""); -System.out.println ("intstaticfinalvar=" + Intstaticfinalvar + ""); theSystem.out.println ("integerstaticfinalvar=" + Integerstaticfinalvar + ""); *System.out.println ("alstaticfinalvar=" + Alstaticfinalvar + ""); $         }Panax Notoginseng  -          Public Static voidMain (String args[]) { the                 Newteststaticfinal (). Test (); +         } A}

Output results

----------strstaticfinalvar=aaastrstaticvar=nullstrfinalvar=nullintstaticfinalvar= before-------------value processing 0integerstaticfinalvar=8alstaticfinalvar=[]----------After-------------value is processed strstaticfinalvar=aaastrstaticvar= haha haha strfinalvar=nullintstaticfinalvar=0integerstaticfinalvar=8alstaticfinalvar=[aaa, BBB] transfer from/HTTP android.blog.51cto.com/268543/384614/

Use of the Java keyword static and final

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.