static 关键字
static 关键字用于创建静态成员,属于类而不是对象。
java
public class Counter {
// static 变量:所有对象共享
private static int count = 0;
// 实例变量:每个对象独立
private int instanceCount = 0;
public Counter() {
count++; // 共享
instanceCount++; // 独立
}
public static int getCount() {
return count;
}
}
// 使用
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
System.out.println(Counter.getCount()); // 3(所有对象共享)
System.out.println(c1.instanceCount); // 1(每个对象独立)static 的四种用法
1. static 变量(类变量)
java
public class Student {
// static 变量:所有学生共享学校名称
public static String schoolName = "Java学校";
private String name;
public static int getTotalStudents() {
return totalCount;
}
}
// 访问方式
Student s1 = new Student("张三");
Student s2 = new Student("李四");
// 推荐:通过类名访问
System.out.println(Student.schoolName); // Java学校
// 也可以通过对象访问(不推荐)
System.out.println(s1.schoolName); // Java学校2. static 方法
java
public class MathUtil {
// static 方法:工具方法
public static int max(int a, int b) {
return a > b ? a : b;
}
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
}
// 调用
int max = MathUtil.max(10, 20);
boolean prime = MathUtil.isPrime(17);3. static 代码块
java
public class DatabaseConfig {
private static String url;
private static String username;
private static String password;
// 静态代码块:在类加载时执行一次
static {
url = "jdbc:mysql://localhost:3306/mydb";
username = "root";
password = "password";
System.out.println("数据库配置加载完成");
}
}4. static 内部类
java
public class Outer {
// static 内部类:不依赖外部类实例
public static class Inner {
public void display() {
System.out.println("静态内部类");
}
}
}
// 使用
Outer.Inner inner = new Outer.Inner();
inner.display();注意事项
1. static 方法不能访问实例成员
java
public class Example {
private int instanceVar = 10;
public static void staticMethod() {
// ❌ 错误:不能访问实例变量
// System.out.println(instanceVar);
// ✅ 正确:通过对象访问
Example obj = new Example();
System.out.println(obj.instanceVar);
}
}2. static 方法中不能使用 this
java
public class Example {
private int value = 10;
public static void staticMethod() {
// ❌ 错误:static 方法中没有 this
// System.out.println(this.value);
}
}3. 静态方法可以被继承和重写吗?
java
class Parent {
public static void staticMethod() {
System.out.println("Parent static method");
}
}
class Child extends Parent {
// 这是隐藏,不是重写
public static void staticMethod() {
System.out.println("Child static method");
}
}
Parent p = new Child();
p.staticMethod(); // Parent static method所以:静态方法没有多态行为。
常见应用场景
1. 工具类
java
public final class StringUtils {
private StringUtils() { } // 私有构造,防止实例化
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
}2. 单例模式
java
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}3. 常量类
java
public class Constants {
public static final int MAX_RETRY = 3;
public static final int PAGE_SIZE = 20;
public static final String DEFAULT_CHARSET = "UTF-8";
}4. 工厂方法
java
public class Connection {
private String url;
private Connection(String url) {
this.url = url;
}
// static 工厂方法
public static Connection create(String url) {
return new Connection(url);
}
}
// 使用
Connection conn = Connection.create("jdbc:mysql://localhost:3306");内存图
┌──────────────────────────────────────────────────────────────┐
│ 方法区(Method Area) │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ 静态变量区 │ │
│ │ ┌────────────────────────────────────────────────┐ │ │
│ │ │ class Counter { │ │ │
│ │ │ static int count = 0; │ │ │
│ │ │ } │ │ │
│ │ │ │ │ │
│ │ │ class Counter 的所有对象共享 count │ │ │
│ │ └────────────────────────────────────────────────┘ │ │
│ └────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
↓
┌──────────────────────────────────────────────────────────────┐
│ 堆内存(Heap) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ Counter │ │ Counter │ │ Counter │ │
│ │ c1 │ │ c2 │ │ c3 │ │
│ │ instance │ │ instance │ │ instance │ │
│ │ Count=3 │ │ Count=3 │ │ Count=3 │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ count 在方法区,所有对象共用一份 │
└──────────────────────────────────────────────────────────────┘总结
| 特性 | 说明 |
|---|---|
| static 变量 | 所有对象共享一份 |
| static 方法 | 属于类,可直接通过类名调用 |
| static 代码块 | 类加载时执行一次 |
| static 内部类 | 不依赖外部类实例 |
记住:static 成员属于类,不属于对象。
