希望这篇文章对你有帮助
静态变量是使用 static 关键字修饰的成员变量,属于类本身而不是某个具体对象。无论创建多少个该类的对象,静态变量在内存中只有一份拷贝,由所有对象共享。
静态变量在类加载时分配内存,直到类卸载时才释放。即使没有创建对象,只要类被加载,静态变量就已经存在。
class Example {
static int value = 10;
static {
System.out.println("类加载,静态变量已初始化:" + value);
}
}
public class Test {
public static void main(String[] args) {
// 未创建对象,静态变量已存在
System.out.println(Example.value);
}
}所有对象共享同一个静态变量,任何一个对象对静态变量的修改,其他对象都能感知。
class Counter {
static int count = 0;
public Counter() {
count++;
}
}
public class Test {
public static void main(String[] args) {
Counter a = new Counter();
Counter b = new Counter();
System.out.println(Counter.count); // 输出2
}
}静态变量可以通过类名或对象名访问,但推荐用类名访问,代码更清晰。
class Demo {
static int n = 5;
}
public class Test {
public static void main(String[] args) {
Demo d = new Demo();
System.out.println(Demo.n); // 推荐
System.out.println(d.n); // 也可以,但不推荐
}
}(详细讲解)
用于统计类被实例化的次数。
class Person {
static int total = 0;
public Person() {
total++;
}
}
public class Test {
public static void main(String[] args) {
new Person();
new Person();
System.out.println("总人数:" + Person.total); // 输出2
}
}存储全局配置信息或常量,方便全局访问。
class Config {
static String APP_NAME = "MyApp";
static final int MAX_USER = 100;
}
public class Test {
public static void main(String[] args) {
System.out.println(Config.APP_NAME);
System.out.println(Config.MAX_USER);
}
}配合静态方法,实现工具类,无需创建对象即可调用。
class MathUtil {
static int add(int a, int b) {
return a + b;
}
}
public class Test {
public static void main(String[] args) {
int sum = MathUtil.add(3, 5);
System.out.println(sum); // 输出8
}
}多线程环境下,静态变量可能被多个线程同时修改,需加锁或使用原子类保证线程安全。
class SafeCounter {
static int count = 0;
public static synchronized void increment() {
count++;
}
}或使用原子类:
import java.util.concurrent.atomic.AtomicInteger;
class SafeCounter {
static AtomicInteger count = new AtomicInteger(0);
public static void increment() {
count.incrementAndGet();
}
}静态变量生命周期长,若引用大对象且未及时释放,可能导致内存泄漏。
class Cache {
static List<byte[]> data = new ArrayList<>();
// 若data一直不清空,内存会持续增长
}静态变量属于类本身,所有对象共享,适合存储全局共享数据。使用时需注意线程安全和内存管理问题。