Explain the use of the static keyword and final keyword in Java programming _java

Source: Internet
Author: User
Tags mathematical constants modifier pow

Java static keywords and Java statics and static methods
The static modifier can be used with a variable, a method, and represents a "static".

Static variables and static methods can be accessed through the class name and do not need to create an object of a class to access the static members of the class, so the members of the static modifier are also called class variables and class methods. Static variables differ from instance variables, and instance variables are always accessed through objects because their values differ between objects and objects.

Take a look at the following example:

public class Demo {
  static int i = ten;
  Int J;
  Demo () {
    THIS.J =;
  }
  public static void Main (string[] args) {
    System.out.println ("Class variable i=" + demo.i);
    Demo obj = new demo ();
    SYSTEM.OUT.PRINTLN ("instance variable j=" + OBJ.J);
  }

Run Result:

Class variable i=10
instance variable j=20


Static memory allocation

A static variable belongs to a class and does not belong to any independent object, so you can access static variables without creating an instance of the class. This results because the compiler creates only a copy of a static variable for the entire class, that is, only one memory space is allocated, although there are multiple instances, but these instances share the memory. Instance variables are different, each create an object, will be allocated a memory space, the different variables of the memory independent of each other, changing the object of A's instance variable does not affect the B object.

Take a look at the following code:

public class Demo {
  static int i;
  Int J;
  public static void Main (string[] args) {
    demo obj1 = new Demo ();
    obj1.i = ten;
    OBJ1.J =;
    
    Demo Obj2 = new Demo ();
    
    System.out.println ("obj1.i=" + obj1.i + ", obj1.j=" + obj1.j);
    System.out.println ("obj2.i=" + obj2.i + ", obj2.j=" + OBJ2.J);
  }

Run Result:

obj1.i=10, obj1.j=20
obj2.i=10, obj2.j=0

Note: Although static variables can also be accessed through objects, they are not advocated, and the compiler generates a warning.

The above code, I is a static variable, through the obj1 change I of the value, will affect the obj2;j is an instance variable, through obj1 change the value of J, does not affect the obj2. This is because obj1.i and obj2.i point to the same memory space, and OBJ1.J and OBJ2.J point to different memory spaces, see the following figure:

Note: Static variables are initialized when the class is loaded. That is, as long as the class is loaded, it is initialized regardless of whether you use the static variable or not.

Summary: Class variables with the keyword static modifier, when the class loading, the allocation of the memory of the class variables, then the class of the instance object, will share the memory (class variable), any object to the class variable changes, will affect other objects. There are two ways to access the outside: through the object or through the class name.
static method

A static method is a method that cannot be applied to an object. For example, the POW () method of the Math class is a static method, with the syntax Math.pow (x, a), used to compute the a power of x, without creating any math objects when used.

Because a static method cannot manipulate an object, you cannot access the instance variable in a static method, only the static variables of its own class.

You can use static methods in the following situations:
A method does not require access to the state of an object, and its required parameters are provided by explicit parameters (for example, Math.pow ()).
A method only needs to access the static variables of the class.

The reader must note that main () is also a static method and does not operate on any object. In fact, there are no objects at the start of the program, and the main () method is the entry for the program, which is executed and creates the object that the program needs.

A summary of static variables and static methods:
A static method of a class can only access static variables;
A static method of a class cannot call a non-static method directly;
such as access control permission, static variables and static methods can also be accessed through the object, but not recommended;
The current object does not exist in the static method, so it cannot be used, and super is not used, of course;
Static methods cannot be overridden by non-static methods;
The constructor method is not allowed to be declared static;
Local variables cannot be decorated with static.

Examples of static methods:

public class Demo {
  static int sum (int x, int y) {return
    x + y;
  }
  public static void Main (string[] args) {
    int sum = Demo.sum (a);
    System.out.println ("10+10=" + sum);
  }

Run Result:

10+10=20

The static method is invoked without any instances of the class to which it belongs, so there is no this value and the instance variable cannot be accessed, or it can cause a compilation error.

Note: Instance variables can only be accessed through objects and cannot be accessed through classes.
Static initializers (static blocks)

A block is a piece of code surrounded by braces. A static initializer is a static block that exists in a class, outside of a method. Static initializers are used only once when the class is loaded (when the class is first used), often to initialize static variables.

Sample code:

public class Demo {public
  static int i;
  static{
    i = ten;
    System.out.println ("Now in the static block.");
  }
  public void Test () {
    System.out.println ("Test method:i=" + i);
  }
  public static void Main (string[] args) {
    System.out.println ("demo.i=" + demo.i);
    New Demo (). Test ();
  }

The results of the operation are:

Now in the static block.
demo.i=10
Test method:i=10


Static Import

Static import is a new feature of Java 5 that is used to import static and static methods for a class.

Generally we import the class to write like this:

Import Packagename.classname; To import a particular class


Or

Import packagename.*; Import all classes in a package

Static import can be written like this:

Import static packageName.className.methonName; To import a specific static method


Or

Import static packagename.classname.*; Import all static members in a class

Once imported, static methods can be invoked directly in the current class with the method name, without having to be accessed by Classname.methodname.

For static variables and static methods that are frequently used, you can import them statically. The advantage of static import is that you can simplify some operations, such as output statement System.out.println (); The out is the static variable of the System class, which can be java.lang.system.* by import static; Import it, the next time you call OUT.PRINTLN () directly.

Take a look at the following code:

Import static java.lang.system.*;
Import static java.lang.Math.random;
public class Demo {public
  static void Main (string[] args) {
    out.println ("A random number produced:" + random ());
  }

Run Result:

Generated by a random number: 0.05800891549018705

Java Final keyword: block inheritance and polymorphism
In Java, when declaring classes, variables, and methods, you can use the keyword final to modify them. Final modified data has a "final state" characteristics, indicating "ultimate" meaning. The specific provisions are as follows:
The final decorated class cannot be inherited.
The final-decorated method cannot be overridden by a quilt class.
A final-decorated variable (member variable or local variable) becomes a constant and can only be assigned one time.
The final decorated member variable must be assigned at the same time as the declaration, and if it is not assigned at the time of the Declaration, there is only one chance to assign the value, and it can only be explicitly assigned in the construction method before it can be used.
The final decorated local variable can only declare no value, and then make a one-time assignment.

Final is generally used to modify the versatility of the function, implementation or value can not be arbitrarily changed data, in order to avoid misuse, such as the implementation of mathematical trigonometric methods, power operations and other functions of the method, as well as mathematical constants π=3.141593, e=2.71828 and so on.

In fact, to ensure the final state, the Java.lang.Math class, which provides the above methods and constants, has also been defined as final.

Note that if you mark a variable of a reference type (the type of any class) as final, then the variable cannot point to any other object. But you can change the object's content, because only the reference itself is final.

If the variable is marked final, the result is to make it a constant. Changing the value of the final variable will result in a compilation error. The following is an example of a correctly defined final variable:

public final int max_array_size = 25; Constant names generally uppercase


Constants cannot be inherited because they have final adornments.

Take a look at the following code:

Public final class demo{public
  static final int total_number = 5;
  public int id;
  Public Demo () {
    //illegal, two-time assignment to final variable Total_number
    //Because ++total_number is equivalent to total_number=total_number+1
    ID = ++total_number;
  }
  public static void Main (string[] args) {
    final demo t = new demo ();
    final int i = ten;
    final int J;
    j =;
    j = 30; Illegal, assign two times to final variable
  }
}

Final can also be used to modify the class (put in front of the class keyword) to prevent the class from deriving subclasses, for example, Java.lang.String is a final class. This is done for security reasons, because to ensure that once a reference to a string is used, it must be a string of class string rather than a string of some other class (A string class can be maliciously inherited and tampered with).

The method can also be modified by final, the final modified method cannot be overridden, and the variable can be final decorated, and the final modified variable will not allow changes to its value after the object is created. Once a class is declared final, the method contained in the class will also be implicitly declared final, but the variable is not.

The final modified method is static binding, does not produce polymorphic (dynamic binding), the program does not need to retrieve the method table at run time, can improve the execution efficiency of the code. In Java, a method that is modified by static or private is implicitly declared final because dynamic binding is meaningless.

Because dynamic binding consumes resources and is often unnecessary, there are some programmers who think that all methods should be final decorated unless there is sufficient reason to use polymorphism.

This kind of understanding is somewhat extreme, because the real-time compiler in the JVM can monitor the running information of the program in real time, and can know the inheritance relationship between classes accurately. If a method is not overwritten and is short, the compiler can optimize it, which is called inline (inlining). For example, an inline call to E.getname () is replaced by an access e.name variable. This is a significant improvement, because the branch transfer used by the CPU when it handles calls to the method will disrupt the policy of the prefetch instruction, so this is considered unwelcome. However, if GetName () is overridden in another class, the compiler cannot know what the overwritten code will do, and therefore cannot inline it.

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.