关于静态成员变量的问题
在下面的代码中,我假设成员变量mBar
只会在第一次构造Foo
对象时实例化......并且这个mBar
实例化将与所有未来的 Foo
对象共享,但 Bar()
构造函数不会再次被调用。这准确吗?
public class Foo {
private static Bar mBar = new Bar();
public Foo() {
}
In the following code, it is my assumption that the member variable mBar
will only be instantiated upon the first construction of a Foo
object... and that this mBar
instantiation will be shared with all future Foo
objects, but the Bar()
constructor will not be called again. Is this accurate?
public class Foo {
private static Bar mBar = new Bar();
public Foo() {
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
该对象实际上可能是在创建第一个 Foo 之前构建的。当 Classloader 将 Foo.class 加载到内存中时,它将执行,这几乎可以随时发生......特别是当您加载使用 Foo 类的其他类时,或者当你调用类的静态方法时......
The object might actually be constructed WAY before creation of first Foo.. It will be executed when Classloader loads the Foo.class in memory and this can happen pretty much at any time.... Specifically when you load other classes that use Foo class, or when you call a static method of the class....
几乎,它会在 class Foo 首次加载时被实例化。因此,如果您调用 Foo.mBar(如果它是公共的),您将获得 bar 实例,即使没有实例化 Foo 实例。
Almost, it will get instantiated when the class Foo is first loaded. So if you call Foo.mBar (if it were public) you would get the bar instance, even though no instances of Foo have been instantiated.
你的假设大多是准确的。 mBar 仅对该类的所有实例(在同一进程中)初始化一次。请注意,这不会阻止任何其他类调用 Bar 构造函数...
编辑:正如注释中所指出的,它不一定是在第一次构造 Foo 对象时;这是对 Foo 对象的第一个执行引用,它将导致类加载器初始化静态成员(从而调用 Bar())。
Your assumptions are mostly accurate. mBar only gets initialized once for all instances of the class (in the same process). Note that that doesn't stop any other classes from calling the Bar constructor...
Edit: as pointed out in the comments, it won't necessarily be upon the first construction of a Foo object; it's the first executing reference to a Foo object that will cause the classloader to initialize the static members (thereby calling Bar()).