假设我有一个静态方法increment:
public class StaticTest {
private static int no = 0;
public static void increment()
{
no++;
}
}
当我使用
StaticTest.increment()
语法调用increment方法时,该类是否被实例化?如果堆上不存在该类型的对象怎么办?StaticTest.increment()
语法调用增量时,类是否会被实例化?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
静态变量将具有值 3
。
如果堆上不存在该类型的类会怎样呢?
那么类加载器将加载它。
将上述代码与以下代码进行对比(没有 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"
new ClassName()
(如果类名为ClassName
)时都会创建。static
关键字使您的声明独立于类的任何实例(对象)。StaticTest.increment()
时,不会创建类StaticTest
的任何对象(也不需要创建对象)。你可以通过使用new StaticTest
来实例化一个对象,除非你已经创建了这样的对象,否则你还没有创建实例。