Reproduced Java base _final and static differences

Source: Internet
Author: User
Tags modifier unique id

In the Java keyword,static and final are two of the keywords we have to master. Unlike other keywords, they are used in a variety of ways, and can improve the performance of the program and optimize the structure of the program in a certain environment. Let's look at the final keyword and the static keyword and how to use it.

Static acts on member variables to indicate that only one copy is saved, and final is used to ensure that the variable is not mutable

Reprint Source:

Https://www.cnblogs.com/dotgua/p/6357951.html

http://www.cnblogs.com/dotgua/p/6354151.html#3929669final keywords

In Java, the final meaning is slightly different from one scenario to another, but in general it refers to " this is immutable ". Below, let's talk about the Final four main uses.

1. Retouching data

When writing a program, we often need to explain that a data is immutable and we become constants. In Java, a variable modified with the final keyword can only be assigned once, and its value cannot be changed during the lifetime. More importantly, final will tell the compiler that this data will not be modified, so the compiler may be able to replace the data or even perform calculations at compile time, which can optimize our program. However, there are subtle differences in the effect of the final keyword when it comes to basic types and reference types. Let's take a look at the following example:

classValue {intv;  PublicValue (intv) { This. v =v; }} Public classFinaltest {Final intF1 = 1; Final intF2;  Publicfinaltest () {F2= 2; }     Public Static voidMain (string[] args) {Final intvalue1 = 1; //value1 = 4; error, value1 not modifiable        Final Doublevalue2; value2= 2.0; FinalValue Value3 =NewValue (1); VALUE3.V= 4; }}

In the example above, let's take a look at some of the final modified data in the Main method, after assigning the initial value to value1, we can no longer modify the value of value1, the final keyword plays a constant role. from value2 we can see that thefinal modified variable can not be assigned a value at the time of Declaration, that is, it can be declared first and then assigned . Value3 a reference variable, here we can see the final modified reference variable, only to qualify the reference variable reference is immutable, that is, you cannot reference another value object Value3, but the value of the referenced object can be changed , From the memory model we see more clearly:

, the final decorated value is represented by a thick border that its value is immutable, and we know that the value of the reference variable is actually the address of the object it refers to, meaning that the value of the address is immutable , which explains why the reference variable cannot be changed by the reference object. The actual referenced object is actually not affected by the final keyword, so its value can be changed.

On the other hand, we see the slight difference in the final modification of member variables, because the value of the final modified data is immutable, so we have to make sure that the member variable is already assigned before it is used. So for a final modified member variable, we have and only two places to assign it, one to declare the member and the other to assign it in the constructor, and in these two places we have to give them an initial value.

Finally, one thing to note is that members using both static and final adornments occupy only a certain amount of storage space that cannot be changed in memory.

2. Modification method Parameters

As we can see earlier, if the variable is created by ourselves, then using the final decoration means that we will only assign it a value once and not change the value of the variable. So if the variable is passed in as a parameter, how do we guarantee that its value will not change? This is the second use of final, that is, when we write a method, we can add the final keyword before the parameter, which means that in the entire method, we don't (actually can't) change the value of the parameter:

 Public class finaltest {    /**    /publicvoid Finalfunc (final  intfinal  value value) {        //  i = 5; Cannot change the value        of I // v = new value (), cannot change the value        of V // You can change the value of a reference object     }}

3. Modification methods

The third way, the final keyword decoration method, indicates that the method cannot be overwritten. This use is mainly from the design perspective, that is, explicitly tell other programmers who might inherit the class, do not want them to overwrite this method. This approach is easy to understand, however, there is a little connection between the private and final keywords, which is that all private methods in the class are implicitly specified as final and cannot be overwritten because the private method cannot be used outside the class.

4. Modifier class

Knowing the other uses of the final keyword, it is easy to think of the effect of using the final keyword to decorate the class, which is that a final decorated class cannot be inherited.

We have explained the Final four usages, but we seldom use them for the third and fourth uses. This is not unreasonable, from the final design, these two usages can even be said to be a chicken, because for developers, if we write a class is inherited more, it means that the class we write more valuable, the more successful. even from a design standpoint, it is not necessary to design a class to be non-inheritable. The Java standard Library is a good example, especially in Java 1.0/1.1, where vector classes are so widely used that it may be more useful if none of the methods are specified as final. For such useful classes, it is easy to think of inheriting and rewriting them, however, due to the final effect, we have been hindered by the expansion of the Vector class, which has caused the vector to not fully realize its full value.

Summarize

The final keyword is one of the keywords that we use a lot, but not every usage is worth our extensive use. Its main uses are the following four types:

    1. Used to modify data, including member variables and local variables, which can only be assigned once and whose values cannot be changed. For a member variable, we must assign a value to it either at declaration time or in the constructor method;
    2. Used to modify a method parameter to indicate that its value cannot be changed during the lifetime of the variable;
    3. A modification method that indicates that the method cannot be overridden;
    4. Modifies the class to indicate that the class cannot be inherited.

Of the four methods above, the third and fourth methods need to be used with caution, because in most cases we do not need to use final to decorate methods and classes, if only for the sake of design considerations.

Static keyword 1. Modifying member variables

In our usual use, the most common function of static is to modify the properties and methods of the class, so that they become the members of the class properties and methods, we usually use static modified members are called Class members or static members, this sentence is very strange, in fact, this is relative to the object's properties and methods. Take a look at the following example: (no program is too bloated, temporarily regardless of access control)

public class Person {    String name;    int age;        Public String toString () {        return ' name: ' + name + ', Age: ' + age;    }        public static void Main (string[] args) {person        p1 = new Person ();        P1.name = "Zhangsan";        P1.age = ten;        person P2 = new person ();        P2.name = "Lisi";        P2.age = n;        System.out.println (p1);        System.out.println (p2);    }    /**output     * Name:zhangsan, age:10     * name:lisi, age:12     *///~}

We are familiar with the above code, each object constructed according to the person is independent, save has its own independent member variables, do not affect each other, their in-memory schematic is as follows:

As you can see, the objects referenced by the P1 and P2 two variables are stored in different addresses in the in-memory heap area, so they do not interfere with each other. But in fact, in this, we omit some important information, I believe you will also think that the object's member properties are here, by each object to save themselves, then their method? In fact, no matter how many objects a class creates, their methods are the same:

As we can see from the above figure, the method of the two person object is actually pointing to the same method definition. This method is defined as an invariant area in memory (divided by the JVM), which we temporarily call a static storage area. this piece of storage not only stores the definition of the method, but actually, from a larger point of view, it holds the definitions of the various classes, and when we build the object through new, the object is created according to the definition of the class defined here. Multiple objects will only correspond to the same method, here is a convincing reason, that is, regardless of how many objects, their methods are always the same, although the final output will be different, but the method will always follow the results we expected to operate, that is, different objects to invoke the same method, the results will vary.

We know that the Static keyword can modify member variables and methods to make them belong to the class, not the object, for example, if we decorate the age property of the person with static, what will the result be? Take a look at the following example:

public class Person {    String name;    static int age;        /* The rest of the code does not change ... */    /**output     * Name:zhangsan, age:12     * name:lisi, age:12     *///~}

We find that the result has changed a bit, and when assigning a value to the age property of P2, it interferes with the P1--which is why? We're still looking at their in-memory schematic:

We found that after adding the static keyword to the age attribute, the person object would no longer have the age property, and the age attribute would be uniformly assigned to the person class to manage, that is, multiple person objects would only correspond to an age property. If an object changes the Age property, the other objects are affected. We see that at this time the Age and ToString () methods are all managed by the class.

Although we see static to allow objects to share properties, we rarely use them in practice, and we don't recommend it. Because it makes this property difficult to control, it can be changed everywhere. If we want to share attributes, we will generally use other methods:

public class Person {    private static int count = 0;    int id;    String name;    int age;        Public person () {        id = ++count;    }        Public String toString () {        return ' ID: ' + ID + ', Name: ' + name + ', Age: ' + age;    }        public static void Main (string[] args) {person        p1 = new Person ();        P1.name = "Zhangsan";        P1.age = ten;        person P2 = new person ();        P2.name = "Lisi";        P2.age = n;        System.out.println (p1);        System.out.println (p2);    }    /**output     * id:1, Name:zhangsan, age:10     * id:2, Name:lisi, Age:12     *///~}

The code above has the effect of creating a unique ID for the person's object and the total number of records, where count is decorated by static and is a member property of the person class, and each time a person object is created, the property is added 1 and then assigned to the object's ID property, so that The Count property records the total number of person objects created, and because Count uses the private adornment, it cannot be arbitrarily changed from outside the class.

2. Modify Member Methods

Another function of static is to modify the member method. The modified member method has little variation over the storage of the data compared to the modified member property, as we can see from the above that the method is stored in the definition of the class. The static modifier member method has the greatest effect of using the " class name. Method Name " method to avoid the tedious and resource consumption of the new object first, and we may often see it used in the Help class:

public class Printhelper {public    static void print (Object o) {        System.out.println (o);    }        public static void Main (string[] args) {        printhelper.print ("Hello World");}    }

The above is an example (not very practical now), but we can see its role, so that the static modified method becomes the method of the class, when used by the " class name, method name " Way can be easily used, Equivalent to defining a global function (as long as you import the package that contains the class). But it also has limitations, a static decorated class that cannot use non-static decorated member variables and methods, which is well understood, because the static modification method belongs to the class, if you go directly to the object's member variables, It will be overwhelmed (I don't know which object's properties to use).

3. Static block

When explaining the third use of the static keyword, it is necessary to re-comb the initialization of an object. Take the following code as an example:

Package Com.dotgua.study;class book{Public book    (String msg) {        System.out.println (msg);}    } public class People {book    Book1 = new book ("BOOK1 member variable Initialization");    Static book Book2 = new book ("Static member BOOK2 member variable Initialization");        Public person (String msg) {        System.out.println (msg);    }        Book BOOK3 = new book ("BOOK3 member variable Initialization");    Static book Book4 = new book ("Static member BOOK4 member variable Initialization");        public static void Main (string[] args) {person        p1 = new Person ("P1 initialization");    }    /**output     * Static member BOOK2 member variable initialization *     static member BOOK4 member variable initialization *     BOOK1 member variable initialization *     BOOK3 member variable initialization     * P1 Initialize     *///~}

In the above example, the person class is composed of four book member variables, two are ordinary members, and two are static decorated class members. As we can see, when we new a person object, the static decorated member variable is initialized first, then the normal member, and finally the constructor method of the person class is initialized. That is, when the object is created, the static decorated member is initialized first, and we can see that if there are more than one static decorated member, it will be initialized according to their position.

In fact, the initialization of a static decorated member can be done earlier, see the following example:

Class book{Public book    (String msg) {        System.out.println (msg);}    } public class People {book    Book1 = new book ("BOOK1 member variable Initialization");    Static book Book2 = new book ("Static member BOOK2 member variable Initialization");        Public person (String msg) {        System.out.println (msg);    }        Book BOOK3 = new book ("BOOK3 member variable Initialization");    Static book Book4 = new book ("Static member BOOK4 member variable Initialization");        public static void Funstatic () {        System.out.println ("Static decorated Funstatic method");        public static void Main (string[] args) {        person.funstatic ();        System.out.println ("****************");        person P1 = new person ("P1 initialization");    }    /**output     * Static member BOOK2 member variable initialization *     static member BOOK4 member variable initialization     * Static modified Funstatic method     * ************* * *     BOOK1 member variable initialization     * BOOK3 member variable initialization     * p1 initialization     *///~}

In the above example we can find two interesting places, the first is when we do not create the object, but through the class to invoke the class method, although the method does not use any of the class Members, class members or before the method call initialization, which means that when we first go to use a class, The member initialization of the class is triggered. The second is that when we use the class method, after initializing the members of the class, and then new to the object of the class, the static decorated class member is not initialized again, which means that the static decorated class member, in the process of running the program, only need to initialize once, and will not be initialized more than once.

After reviewing the initialization of the object, it is very simple to look at the third function of static, that is, when we initialize the members of the static modifier, we can place them uniformly in a block statement that begins with a static, wrapped in curly braces:

Class book{Public book    (String msg) {        System.out.println (msg);}    } public class People {book    Book1 = new book ("BOOK1 member variable Initialization");    static book Book2;        static {        Book2 = new book ("Static member BOOK2 member variable Initialization");        BOOK4 = new book ("Static member BOOK4 member variable Initialization");        Public person (String msg) {        System.out.println (msg);    }        Book BOOK3 = new book ("BOOK3 member variable Initialization");    static book Book4;        public static void Funstatic () {        System.out.println ("Static decorated Funstatic method");        public static void Main (string[] args) {        person.funstatic ();        System.out.println ("****************");        person P1 = new person ("P1 initialization");    }    /**output     * Static member BOOK2 member variable initialization *     static member BOOK4 member variable initialization     * Static modified Funstatic method     * ************* * *     BOOK1 member variable initialization     * BOOK3 member variable initialization     * p1 initialization     *///~}

We will make a slight change to the previous example, and we can see that the result is not two.

4. Static Guide Package

Compared to the three uses above, the fourth use may be less, but in fact it is very simple, and it is more convenient to call the class method. Take the example of "Printhelper" above, and make a slight change, and you can use the static guide to give us the convenience:

/* Printhelper.java file */package Com.dotgua.study;public class Printhelper {public    static void print (Object o) {        System.out.println (o);    }}
/* App.java file */

Import static com.dotgua.study.printhelper.*;p Ublic class App {public static void Main (string[] args) { PR Int ("Hello world!"); } /**output * Hello world! *///~}

The code above comes from two Java files, where the Printhelper is simple and contains a static method for printing. In the App.java file, we first import the Printhelper class, where we use the static keyword when we import it, and at the end of the introduction class are added ". *", Its purpose is to import all the class methods in the Printhelper class directly. Unlike a non-static import, with the static import package, without a conflict with the method name of the current class, you do not need to use the " class name. Method Name" method to invoke the class method, directly using the " method name " To invoke the class method, It is as if it were the same as the class's own method.

Summarize

Static is a very important keyword in Java, and its usage is very rich, there are four main ways to use it:

    1. Used to modify a member variable to become a member of a class, thus realizing the sharing of all objects with that member;
    2. Used to modify a member method and make it a class method, which can be called directly using the "class name. Method Name" , which is commonly used in tool classes;
    3. Static block usage, the initialization of multiple class members, makes the program more regular, in which the initialization process of understanding objects is very critical;
    4. Static Guide Package usage, the method of the class is imported directly into the current class, thus directly using the "method name" to invoke the class method, more convenient.

final can modify variables, methods, and classes:

When a final variable is defined, the JVM assigns it to a constant pool, and the program cannot change its value;

When a method is decorated, the method cannot be overridden in subclasses;

When a class is decorated, the class cannot be inherited.

Static is a statically decorated keyword that can modify variables and blocks and class methods:

When a static variable is defined, the JVM allocates it to the memory heap, and all references to it will point to that address without reallocating the memory;

When modifying a program block (that is, writing code directly in the static{...} , the virtual machine loads the code in the static block first, which is used primarily for system initialization;

When you modify a class method, you can call it directly from the class without needing to create a new object.

Reproduced Java base _final and static differences

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.