java静态实例字段和构造函数 [英] java static instance fields and constructor

查看:72
本文介绍了java静态实例字段和构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有静态实例字段的Java类中,构造函数是在每次访问字段时才调用,还是仅在首次访问时调用?我在构造函数中初始化了静态字段,并想知道这是否会导致速度降低,因为每次访问都将初始化字段。

In a Java class with static instance fields, is the constructor called every time the fields are accessed, or only on the first access? I initialize the static fields in the constructor, and was wondering if this would cause a slow down because the fields are initialized on every access.

推荐答案


我在构造函数中初始化静态字段,

I initialize the static fields in the constructor,

不要。切勿在构造函数内部初始化静态字段。 static 字段与类的任何实例都不相关。它必定要上课。该变量只有一个副本,可在所有实例中访问。因此,如果要在构造函数中对其进行初始化,则每次创建实例时,该字段都会为其他每个实例重新初始化。

Don't. Never initialize static fields inside a constructor. static fields are not something associated with any instance of a class. It is bound to class. There is only single copy of that variable, that is accessed accross all the instances. So, if you are initializing it in constructor, then every time you create an instance, that field will be re-initialized for every other instance.

您应使用静态初始值设定项块来初始化您的静态字段,或仅在声明位置进行初始化。

You should use static initializer block to initialize your static fields, or just initialize them at the place of declaration.

class Demo {
    private static int x;  // Either initialize it here.

    static {   // Or use static initializer block
        x = 10;
    }
}




具有静态实例字段,是每次访问字段时都会调用的构造函数。

with static instance fields, is the constructor called every time the fields are accessed,

否。,静态字段在。当加载类时,将加载并初始化它们。然后您可以稍后在类名上对其进行修改,在这种情况下,更改将对所有实例生效。因此,只要您访问静态字段,就不会调用构造函数。

No. , static fields are accessed on class. They are loaded and initialized when the class is loaded. And then you can modify it later on, on class name, in which case, the change will be effected for all the instances. So, the constructor will not be invoked, whenever you access static field.

实际上,即使您访问实例字段,构造函数也不会每次都被调用。构造函数用于初始化一次新创建实例的状态。为了进一步访问和修改该字段,将不会调用构造函数

In fact, even when you access instance field, constructor is not invoked every time. Constructor is used to initialize the state of the newly created instance once. And for further access and modification of that field, constructor won't be invoked.

因此,构造函数具有当您想访问班级中的任何字段时,完全没有任何作用。

So, a constructor has precisely no role to play whenever you want to access any fields of your class.

这篇关于java静态实例字段和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆