The use of static and final keywords for Java

Source: Internet
Author: User
Tags rand

Use of the Static keyword

static means "' static," which can be used to modify properties and methods in Java.

  The application of the static keyword should be noted in the following scenarios:  

    1.static acts on a field, and a static field has only one copy of the storage space for each class, instead of a static field where each object has a copy of the storage space.

2.static an important use of the method is that you do not need to create any objects to call the static method directly, which is important for the main () method.

3.static cannot be applied to local variables.

Global methods are not allowed in 4.Java, so the introduction of the static method is called directly through the class itself.

 Packagecn.wangze.test;classdemo{ Public Static inti = 19;} Public classStaticdemo {Private StaticDemo Demo1 =NewDemo (); Private StaticDemo Demo2 =NewDemo ();  Public Static voidMain (string[] args) {System.out.println (DEMO.I); // +System.out.println (DEMO1.I);// +System.out.println (DEMO2.I);// +demo1.i++;        System.out.println (DEMO.I); // -System.out.println (DEMO1.I);// -System.out.println (DEMO2.I);// -demo.i++;        System.out.println (DEMO.I); // +System.out.println (DEMO1.I);// +System.out.println (DEMO2.I);// +    }}

The output of the above program verifies that the above two, the data with the static keyword occupies a fixed memory address in memory, you can call directly with the class name, you can create an object to invoke, recommend Classname.method () to call. When we change its value, the call from anywhere will change.

  The Java system comes with math, UUID, class, and other commonly used tool classes that are used in this way.

 Why are methods and variables written as static?
Because, these methods I just want to invoke, do not need to involve any of the properties and variables in the tool class, so I do not need to instantiate (new). Since there is no need to instantiate, then use static on the line.

You can also declare your own tool classes in real-world projects based on business requirements, just add the static keyword, and use the class name after the class is introduced. The method name () is called.

It is important to note that during the loading and initialization of classes, the data with static is loaded and called first, followed by the constructor's loading, and finally the normal member variables and methods are loaded.

Usage of final keyword

  Final means "immutable" and is generally applied to data, methods, and classes.

Final data

When the data is a basic type, it means that this is a never-changing compile-time constant, a value that is initialized at runtime, and you don't want it to change.

When the data is a reference type, the static and final adornments indicate that it occupies only a block of memory space that cannot be changed.

One of the conventions idiomatic is that variables that use Stati and final modifiers, i.e. compile-time constants, should be represented in all uppercase letters, for example:

 Packagecn.wangze.test;ImportJava.util.*;classvalue{inti;  PublicValue (inti) {         This. i =i; }} Public classFinalData {Private StaticRandom Rand =NewRandom (47); PrivateString ID;  PublicFinalData (String id) { This. ID =ID; }    Private Final intValue_one = 9; Private Static Final intValue_two = 99;  Public Static Final intValue_three = 39; Private Final intI4 = Rand.nextint (20); Static Final intInt_5 = Rand.nextint (20); PrivateValue V1 =NewValue (11); Private FinalValue v2 =NewValue (22); Static FinalValue V3 =NewValue (33); Private Final int[] A = {1,2,3,4,5,6}; @Override PublicString toString () {returnId+ ", i4=" +i4+ ", int_5 =" +int_5; }     Public Static voidMain (string[] args) {FinalData fd1=NewFinalData ("Fd1"); //fd1.value_one++; error, the value of the basic type data of the final decoration cannot be changedfd1.v2.i++; Fd1.v1=NewValue (9);//can be manipulated because V1 is not final data//fd1.v2 = new Value (0); Error, the memory address of the final decorated reference type data cannot be changed//fd1.v3 = new Value (5); Error, the memory address of the final decorated reference type data cannot be changed//fd1.a = new Int[3]; /error, the memory address of the final decorated reference type data cannot be changedSystem.out.println (FD1);//fd1, i4=15,int_5 =SYSTEM.OUT.PRINTLN ("Creating New FinalData"); FinalData FD2=NewFinalData ("Fd2");     System.out.println (FD1); //fd1, i4=15,int_5 =System.out.println (FD2);//fd2, i4=13,int_5 =    }}

The above example verifies the difference between the basic data type and the reference data type of the final decoration. According to the output values of I4 and int_5, we can conclude that at compile time we cannot know its value because the data is final, and only when it is run will it be determined by its value. At the same time, static and non-static differences are shown, and data with the Static keyword is initialized at load time, and non-static data is initially recognized at the time the object was created. For example:

 Packagecn.wangze.test;classusedemo{Private inti;  PublicUsedemo (intII) {i=II; }} Public classblankfinal {Private Final inti = 9; Private Final intJ; Private FinalUsedemo ud;  Publicblankfinal () {J= 1; UD=NewUsedemo (10); }     PublicBlankfinal (intx) {J= 2; UD=NewUsedemo (x); }     Public Static voidMain (string[] args) {Newblankfinal (); NewBlankfinal (55); }}

In the example above we are not assigning a value to a final variable, which is not wrong, but it must be assigned in the constructor, otherwise the compilation will not pass.

 2. FIANL parameters

When we define the method passed in as fianl, we do not want to change the reference of this parameter within the method.

     Public void Final Usedemo U2) {        = +;         // U2 = new Usedemo (20); Error    

The fact is that when we do not have the final keyword, the reference changes inside the function will not affect the external arguments, so I think the final role here is the compile-time block, play a warning role.

  3. Fianl method

In general, we use the final method to prevent subclasses from overwriting or modifying such methods.

All private methods in the class are implicitly set to final. Because the private method only displays in this class, the method cannot be manipulated even by subclasses. Sometimes we declare a method with the same name in the subclass as the private method of the parent class, so that we don't get an error, and we don't actually overwrite or modify the private method of the parent class, it's just a new method with the same name as the parent private method.

4, FIANL class

    In general, we use the final class to show that we do not intend to inherit the class with any class, that is, we do not want the class to have subclasses.

A class with the final keyword, all of its internal methods and data are implicitly with the final keyword, because no class can inherit the class, representing any external factors that can change its data.


When we design the program, it is important to determine whether the data or method or class has static and final keywords based on the business requirements, and from another point of view, the rational application of the final and static keywords can actually improve the efficiency of the program and reduce the consumption of memory. When we understand the initialization and loading process of classes, it is possible to have a more intuitive understanding of final and static.

The use of static and final keywords for Java

Related Article

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: 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.