gpt4 book ai didi

java - 使用静态方法时,类是否每次都被实例化?

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:18 25 4
gpt4 key购买 nike

假设我有一个静态方法增量:

public class StaticTest {
private static int no = 0;

public static void increment()
{
no++;
}
}

当我使用 StaticTest.increment() 语法调用 increment 时,类是否会被实例化?如果堆上不存在该类型的对象怎么办?

最佳答案

When I call increment using the StaticTest.increment() syntax, does the class ever get instantiated?

本身会被加载(由类加载器),如果它还没有被加载的话。如果已经加载,则不会加载第二次。没有创建该类的实例(该类类型的对象),因为您还没有创建任何实例。

假设所有调用 StaticTest.increment() 的代码都使用相同的类加载器(通常是这种情况),有多少不同的代码位调用该静态方法并不重要,只使用该类的一个副本。他们都分享它。例如:

// Some bit of code somewhere
StaticTest.increment();

// Another bit of code somewhere else
StaticTest.increment();

// A third bit of code in yet another place
StaticTest.increment();

所有这些都运行后,StaticTest 中的 no 私有(private)静态成员的值为 3

What if no class of that type exists on the heap already?

然后类加载器加载它。


将该代码与此对比(无 static):

public class NonStaticTest {
private int no = 0;

public void increment()
{
no++;
}

public int getNo() // So we can see the results
{
return no;
}
}

现在,我们不能这样做:

NonStaticTest.increment(); // WRONG, fails with error saying `increment` is not static

我们这样做:

NonStaticTest instance = new NonStaticTest();
instance.increment();
System.out.println(instance.getNo()); // "1"

第一次 时间代码执行此操作,NonStaticTest 类由类加载器加载。然后,new NonStaticTest() 表达式创建该类的一个实例,它有一个no 成员。 second 时间代码执行此操作,NonStaticTest 已加载,因此不会再次加载。然后 new NonStaticTest() 表达式创建该类的第二个实例

如果我们有三位代码都执行上述操作,他们每个人都会看到“1”,因为no 特定于类的实例,而不是依附于类(class)本身。

关于java - 使用静态方法时,类是否每次都被实例化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23404845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com