Home » Java » Java static fields and static methods

Java static fields and static methods

Java static domains and static methods

@ (blog post) [java]


in Java, the static modifier static can only be used for class member variables and member methods.


(1) static domains
1, static variables

if a variable is defined as static, then the class and all of its objects share the same value. It only exists in memory, and strictly speaking, there is only one copy per JVM.

For example:


public class Employee{
Private int id;
Private, static, int, nextId = 1;
}

each Employee object has a copy of the ID, and their values are not the same. But all Employee share the same nextId value, and it only exists in JVM with one.


2, static constants

in fact, static variables are used relatively little, and they are usually used in combination with some design patterns (such as singleton), but static constants are used very much, such as

in the Math class
public, static, final, double, PI = 3.1415926538979323864;

Another thing that

uses very much is System.out, which is declared in the System class:


public, static, final, PrintStream, out =...

(two) static method

static methods do not have to instantiate objects before calling, and faces can be invoked directly using class names. They are often used in tool classes (utils, etc.), such as many methods in the Math class:


Math.pow (5,2);

static methods cannot manipulate objects and cannot access instance domains in static methods (but access to static domains).


uses the static method in the following 2 cases:

[tools] a method does not require access to the object state, and its required parameters are provided by explicit arguments (such as Math.pow ())

* a method requires only access to the static domain of the class (such as Employee.geetNextId ())


(three) static member class

, please refer to twenty-fourth,


(four) summary

  1. static domains exist only in memory, and all objects are shared. Static constants are more sensible, static variables are more, and.
  2. is used in conjunction with some design patterns
  3. static methods are more useful for tool classes, or for access to static domains of classes only..


Latest