第 5 章:封装、static 与 final
学习目标
- 掌握封装的本质和 getter/setter
- 理解四种访问修饰符
- 学会 static(类成员)和 final(常量)
一、封装:把数据藏起来
封装 = 字段 private + getter/setter 控制读写。
java
class User {
private String name; // 私有字段
private int age;
public String getName() { return name; }
public void setName(String name) {
if (name == null || name.isEmpty()) { // 校验
throw new IllegalArgumentException("姓名不能为空");
}
this.name = name;
}
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException("年龄不合法");
}
this.age = age;
}
}⚠️ 坑 1:所有字段一律
private,外部必须通过 getter/setter 访问,这样可以在 setter 里加校验,防止非法数据。
二、四种访问修饰符
| 修饰符 | 同类 | 同包 | 子类 | 其他包 |
|---|---|---|---|---|
private | ✅ | ❌ | ❌ | ❌ |
| 默认(无) | ✅ | ✅ | ❌ | ❌ |
protected | ✅ | ✅ | ✅ | ❌ |
public | ✅ | ✅ | ✅ | ✅ |
实战口诀:字段 private,工具方法 public,子类扩展方法 protected。
三、static:类级别的成员
static 修饰的成员属于类本身,而不是某个对象。所有对象共享一份。
java
class User {
private static int count = 0; // 类变量:所有 User 对象共享
public User() {
count++; // 每创建一个对象 +1
}
public static int getCount() { // 类方法:可通过类名直接调用
return count;
}
}
new User();
new User();
System.out.println(User.getCount()); // 2(无需创建对象就能调用)⚠️ 坑 2:
static方法里不能直接访问非 static 字段(因为非 static 字段属于对象,而 static 方法调用时可能没对象)。javaclass User { private int age = 18; public static void print() { System.out.println(age); // ❌ 编译报错 } }
四、final:不可修改
java
final int MAX_COUNT = 100; // 常量,不能改
// MAX_COUNT = 200; // ❌ 编译报错
final class StringUtil { } // 类不能被继承
// class MyUtil extends StringUtil { } // ❌
// final 用于方法:子类不能重写(后续继承章节详解)常量命名:UPPER_SNAKE_CASE,全部大写+下划线。
java
public class Constants {
public static final int MAX_RETRY_COUNT = 3;
public static final String DEFAULT_NAME = "游客";
}五、实战:封装 + static 工具类
java
public class StringUtils {
// 工具类构造器私有化,禁止 new
private StringUtils() { }
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
public static String reverse(String s) {
if (isEmpty(s)) return s;
return new StringBuilder(s).reverse().toString();
}
}
// 使用
StringUtils.isEmpty(""); // true
StringUtils.reverse("hello"); // "olleh"⚠️ 坑 3:工具类不需要创建对象,应该把构造器
private掉,防止误用。
六、本章小结
| 要点 | 关键 |
|---|---|
| 封装 | 字段 private + getter/setter,setter 加校验 |
| 访问修饰符 | private(同类)/ 默认(同包)/ protected(子类)/ public(所有) |
| static | 类成员,所有对象共享,可通过类名直接访问 |
| static 方法 | 不能访问非 static 字段 |
| final 变量 | 常量,不能修改 |
| final 类 | 不能被继承 |
动手练习
- 封装 Order:订单类,字段私有,setter 校验(数量 > 0,价格 > 0)
- static 计数器:写
LoginCounter类,用 static 变量统计登录次数 - 工具类:写
ArrayUtils类,提供int[] reverse(int[] arr)静态方法
下一章:第 6 章:继承 →