且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

static关键字如何在Java中工作?

更新时间:2022-05-31 03:37:11

此副本存储在何处?

副本(静态变量)存储在Permanent Geneneration部分中,但如果使用Java8,则永久生成部分不再存在。
静态变量以及静态方法是反射数据的一部分 - 类相关数据而非实例相关。

The copy(static variable) is stored in the Permanent Geneneration section, but if you use Java8 the Permanent Generation section not longer exists. The static variables and also the static methods are part of the reflection data - class related data and not instance related.

对象如何访问该副本?

您创建的每个类(对象)实例都有对该类的引用。

Every instance of class(object) that you have created have a reference to the class.

什么时候创建了这个副本?

它是在加载类时在运行时创建的:这是由类加载器完成的首次引用类时的JVM。

It is created at runtime when the class is loaded: this is done by the classloader of the JVM when the class is first referenced.

静态变量属于类,而不属于类的实例。
所以,你的直觉是对的,不管你创建了多少个对象,你只有一个副本。

Static variables belong to the class, and not to instances of the class. So, your intuition is right, you have only one copy regardless of how many object you create.

你可以使用一个静态变量来访问类的名称,如下例所示:

You can access a static variable using the name of the class, like in this example:

class Static {

    static int staticField;

}

public class UseStatic {

    public static void main(String[] args) {

        System.out.println(Static.staticField);

    }
}

静态字段对于创建某种类常量非常有用。

The static fields are useful to create some kind of class constants.

最后,为了轻松初始化特定类的静态字段,您可以使用静态初始化块

Finally, to easily initialize a static field of a specific class you can use Static Initialization Blocks.

来源:关于java的大学课程, java official文件

Sources: university course on java, java official documentation