静态类什么时候初始化?
考虑 仅包含静态字段的 Java 类并且没有构造函数:
public class OnlyStatic {
static O1 o1 = new o1();
static O2 o2 = new o2();
public static int compute(int whatever) {
return o1.foo+o2.bar+whatever;
}
}
在不同的类中,通过静态导入
使用方法compute
:
static import OnlyStatic.compute
int a = OnlyStatic.compute(3);
或者直接使用,假设调用者位于同一个包中:
int a = OnlyStatic.compute(3);
o1 和o2 初始化了吗?在导入时,还是在第一次调用 compute()
时?
Consider a Java class with static fields only and no constructor:
public class OnlyStatic {
static O1 o1 = new o1();
static O2 o2 = new o2();
public static int compute(int whatever) {
return o1.foo+o2.bar+whatever;
}
}
In a different class, the method compute
is used, either by static import
:
static import OnlyStatic.compute
int a = OnlyStatic.compute(3);
Or directly, assuming the caller is in the same package:
int a = OnlyStatic.compute(3);
When are o1 and o2 initialized? At the import, or when compute()
is called for the first time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果不将对象
o1
和o2
设为static
,它们也无法在您的static
上下文中使用。JVMS 指出
进一步
因此,在您的情况下,当首先执行静态方法compute()时。
The objects
o1
ando2
are not available to yourstatic
context without making themstatic
also.JVMS states that
Further
So in your case, when the static method
compute()
is first executed.