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.

Package Cn.wangze.test;class demo{public    static int i = 19;} public class Staticdemo {    private static demo demo1 = new Demo ();    private static Demo Demo2 = new Demo ();    public static void Main (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:

Package Cn.wangze.test;import java.util.*;class value{int i;    Public Value (int i) {this.i = i;    }}public class FinalData {private static random Rand = new Random (47);    Private String ID;    Public FinalData (String id) {this.id = ID;    } private Final int value_one = 9;    private static final int value_two = 99;    public static final int value_three = 39;    Private final int i4 = Rand.nextint (20);    static final int int_5 = Rand.nextint (20);    Private Value V1 = new value (11);    Private Final Value v2 = new value (22);    Static final Value V3 = new value (33);    Private Final int[] a = {1,2,3,4,5,6};    @Override public String toString () {return id+ ", i4=" +i4+ ", int_5 =" +int_5;        } public static void Main (string[] args) {FinalData fd1 = new FinalData ("Fd1"); fd1.value_one++;        Error, the value of the final modified base type data cannot be changed fd1.v2.i++; FD1.V1 = new Value (9);  Can be manipulated because V1 is not final data//fd1.v2 = new Value (0); Error, final decorated memory for reference type dataAddress 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 changed System.out.println (FD1);        FD1, i4=15,int_5 = System.out.println ("Creating new FinalData");          FinalData fd2 = new FinalData ("Fd2");     System.out.println (FD1);    FD1, i4=15,int_5 = System.out.println (FD2); FD2, i4=13,int_5 = 18}}

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:

Package Cn.wangze.test;class usedemo{    private int i;    Public Usedemo (int ii) {        i = II;    }} public class Blankfinal {    private final int i = 9;    private final int J;    Private final Usedemo ud;    Public blankfinal () {        j = 1;        UD = new Usedemo (ten);    }    public blankfinal (int x) {        j = 2;        UD = new Usedemo (x);    }    public static void Main (string[] args) {        new blankfinal ();        New Blankfinal;    }}

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 Change (final Usedemo U2) {        u2.i =;        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.

Summarize:

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

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.