static关键字用于创建独立于为该类创建的任何实例而存在的变量。无论类的实例数量如何,静态变量只有一个副本存在。
静态变量也称为类变量。局部变量不能声明为静态。
静态修饰符用于创建类方法和变量,如以下示例所示:
public class InstanceCounter { private static int numInstances = 0; protected static int getCount() { return numInstances; } private static void addInstance() { numInstances++; } InstanceCounter() { InstanceCounter.addInstance(); } public static void main(String[] arguments) { System.out.println("Starting with " + InstanceCounter.getCount() + " instances"); for (int i = 0; i < 500; ++i) { new InstanceCounter(); } System.out.println("Created " + InstanceCounter.getCount() + " instances"); } }
输出结果
Started with 0 instances Created 500 instances