Home  >  Article  >  Java  >  What does the static keyword do?

What does the static keyword do?

(*-*)浩
(*-*)浩forward
2019-08-21 15:41:044897browse

Today we mainly study the static keyword in Java language.

What does the static keyword do?

The meaning and usage scenarios of the static keyword

static is one of the 50 keywords in Java. The static keyword can be used to modify code blocks to represent static code blocks, modified member variables to represent global static member variables, and modified methods to represent static methods. (Note: Ordinary classes cannot be modified, except inner classes. Why is this?)

class A {
	static {
		System.out.println("A : 静态代码块");
	}
	
	static int i ;  // 静态变量
	
	static void method() {
		System.out.println("A: 静态方法");
	}
}

In short, the content modified by the static keyword is static.

Static is relative to dynamic. Dynamic means that when a Java program is run on the JVM, the JVM will dynamically create objects and store objects (allocate memory) according to the needs of the program. After the object's mission is completed, the object will be garbage Recycler destruction, that is, memory recycling is managed uniformly by the JVM and allocated to other newly created objects; static means that before the Java program is running, the JVM will allocate space for the loaded class to store the content modified by the static keyword; such as static Member variables, Java classes are loaded into the JVM, and the JVM will store the class and its static member variables in the method area. We know that the method area is an area shared by threads and GC rarely occurs, so the content modified by the static keyword is It is shared globally and storage space will only be allocated once.

So when some content of the class does not belong to the object, but is shared by the object and belongs to the class, you can consider whether to use the static keyword to modify it.

The role of the static keyword

1 Modify the code block

The code block modified with the static keyword in the class is called static code, and vice versa Code blocks that are not modified with the static keyword are called instance code blocks.

The instance code block will be executed as the object is created, that is, each object will have its own instance code block, which means that the running result of the instance code block will affect the content of the current object and will change with the object. is destroyed and disappears (memory recycling); and the static code block is the code block that is executed when the Java class is loaded into the JVM memory. Since the loading of the class only occurs once during the running of the JVM, the static code block will only be executed once. .

Because the main function of the static code block is to perform some complex initialization work, the static code block is stored in the method area following the class in the form that the result of the execution of the static code block is stored in the method area, that is, initialization The quantity is stored in the method area and shared by threads.

2 Modify member variables

The member variables modified with the static keyword in the class are called static member variables, because static cannot modify local variables (why?), so static member variables can also be called is a static variable. Static variables are similar to code blocks. When the class is loaded into the JVM memory, the JVM will put the static variables into the method area and allocate memory, which is also shared by threads. The access form is: class name.static member name.

public class StaticTest {
	public static void main(String[] args) {
		System.out.println(D.i);
		System.out.println(new D().i);
	}
}
class D {
	static {
		i = 2;
		System.out.println("D : 静态代码块1");
	}
	static int i;
}

Static variables are stored in class information and can be shared between threads. Then of course it also belongs to every object of the class, so static variables can be accessed through objects, but the compiler does not support this. Do it and a warning will be given.

Note:

The loading order of static variables of a class and static code blocks of the class. The class will load static variables first, and then load static code blocks. However, when there are multiple static variables and multiple code blocks, they will be loaded in the order in which they are written.

class D {
	static {
		i = 2;
		System.out.println("D : 静态代码块1");
	}
	static {
		i = 6;
		System.out.println("D : 静态代码块2");
	}
	static int i;
}

You can think about the results of the operation.

Static variables do not need to be explicitly initialized, and the JVM will give them corresponding default values ​​by default. For example, the basic data type of byte is 0, short is 0, char is \u0000, int is 0, long is 0L, float is 0.0f, double is 0.0d, boolean is false, and the reference type is uniformly null.

Since static variables are shared in JVM memory and can be changed, accessing them will cause thread safety issues (while thread A is rewriting, thread B obtains its value, then what is obtained is the value before modification) value or modified value?), so when using static variables, multi-threading should be considered. If you can ensure that static variables are immutable, you can use the final keyword to avoid thread safety issues; otherwise, you need to use synchronization to avoid thread safety issues, such as using it with the volatile keyword.

The static key cannot modify local variables, including instance methods and static methods, otherwise it will violate the original intention of the static keyword - sharing.

3 Modified method

The method modified with the static keyword is called a static method, otherwise it is called an instance method. Called through class name.method name, but it should be noted that static methods can directly call static variables and other static methods of the class, but cannot directly call member variables and instance methods (unless called through objects).

class D {
	static {
		i = 2;
		System.out.println("D : 静态代码块");
	}
	static final int i;
	int j;
	
	static void method() {
		System.out.println(i);
		System.out.println(new D().j);
		
		method1();
		new D().method2();
	}
	
	static void method1() {
		System.out.println(i);
	}
	void method2() {
		System.out.println(i);
	}
}

Note: Since the instance methods of a class require object calls to access, and static methods can be accessed directly through the class name, how does a class start executing without considering the deployment server? The biggest possibility is to start Java through "class name.static method", and I define so many static methods, how does the JVM know the main entrance?

Perhaps you thought of the main method.

Yes, the main method is defined by the Java specification as the main entrance of the Java class. The operation of Java classes is started by the main method:

 public static void main(String[] args) {
	for (String arg : args) {   // 参数由外部定义
		System.out.println(arg);
	}}

但注意main并不是Java关键字,它只是一个规定的程序入口的方法名字;另外main方法可以重载。

注意:static关键字虽然不能修饰普通类,但可以用static关键字修饰内部类使其变成静态内部类。static关键字本身的含义就是共享,而Java类加载到JVM内存的方法区,也是线程共享的,所以没必要用static关键字修饰普通类。

4 静态导入

在用import导入包或者类时,可以用static修饰包名或者类,表示静态导入。静态导入可以与动态导入放在一起比较来加深理解。

动态导入是当你程序运行时需要new一个不在此包中的类的对象时,才会根据全路径类名加载类;而静态导入则是随着类的加载而加载静态导入的类,所以它是提前导入的。

public class StaticTest {
	static void method1() {
		System.out.println("static method1");
	}
	
	static void method2() {
		System.out.println("static method2");
	}
}

静态导入:

import static com.starry.staticImport.StaticTest.method1;

public class Client {
	public static void main(String[] args) {
		method1();   // 
		StaticTest.method2();
	}
}

注意method1()是静态导入,所以可以不需要通过类名访问;而method2()没有导入,则需要通过类名调用。那么什么时候需要静态导入呢?

静态导入常用于静态方法以及含有静态方法的类,枚举类等的导入,可以在编译阶段确定导入类的信息或者方法信息。

static关键字的缺点

封装是Java类的三大特性之一,也是面向对象的主要特性。因为不需要通过对象,而直接通过类就能访问类的属性和方法,这有点破坏类的封装性;所以除了Utils类,代码中应该尽量少用static关键字修饰变量和方法

The above is the detailed content of What does the static keyword do?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete