在 Java 中,get
和 set
方法是面向对象编程中 封装(Encapsulation) 的核心实现,用于安全地访问和修改类的私有字段(private
成员变量)。它们的核心作用是 控制对数据的访问,并确保数据完整性。
1. 为什么需要 get
和 set
?
-
直接访问字段的问题:
public class Person {public String name; // 直接暴露字段 }// 外部可直接修改字段,可能导致非法值 Person p = new Person(); p.name = ""; // 名字被设为空字符串(无效值)
-
封装后的安全访问:
public class Person {private String name; // 私有字段,外部无法直接访问// 通过 set 方法控制赋值public void setName(String name) {if (name != null && !name.isEmpty()) {this.name = name; // 只有合法值才允许设置}}// 通过 get 方法提供安全读取public String getName() {return name;} }
2. get
方法(Getter)
- 作用:获取私有字段的值。
- 命名规则:
get + 字段名(首字母大写)
。 - 示例:
public class Person {private int age;// Getter 方法public int getAge() {return age;} }
3. set
方法(Setter)
- 作用:设置私有字段的值,通常包含数据校验逻辑。
- 命名规则:
set + 字段名(首字母大写)
。 - 示例:
public class Person {private int age;// Setter 方法(带校验)public void setAge(int age) {if (age >= 0 && age <= 150) { // 校验年龄合法性this.age = age;} else {System.out.println("年龄无效");}} }
4. 实际使用场景
(1) 数据验证
public class BankAccount {private double balance;public void setBalance(double amount) {if (amount >= 0) { // 禁止设置负数余额this.balance = amount;}}public double getBalance() {return balance;}
}
(2) 延迟加载(Lazy Initialization)
public class DataCache {private List<String> cache;public List<String> getCache() {if (cache == null) { // 首次访问时初始化cache = loadDataFromDatabase();}return cache;}
}
(3) 隐藏实现细节
public class Temperature {private double celsius;// 对外暴露华氏度接口,隐藏内部摄氏度存储public double getFahrenheit() {return celsius * 1.8 + 32;}public void setFahrenheit(double fahrenheit) {this.celsius = (fahrenheit - 32) / 1.8;}
}
- 没有
get/set
:代码会变得脆弱、不可控,容易引发隐蔽的 Bug。
123
public static Component createPathComponent(long pathId) {Component component = new Component(); // 1️⃣ 创建空对象(id=0, type=null, componentId=0)component.setType(ComponentType.PATH); // 2️⃣ 设置 type = PATHcomponent.setComponentId(pathId); // 3️⃣ 设置 componentId = pathIdreturn component; // 3️⃣ 返回对象(id=0, type=PATH, componentId=1001)
}
使用示例
// 创建路径组件(关联路径ID=1001)
Component pathComponent = Component.createPathComponent(1001);// 打印组件信息
System.out.println("类型: " + pathComponent.getType()); // 输出: PATH
System.out.println("组件ID: " + pathComponent.getComponentId()); // 输出: 1001
System.out.println("内部ID: " + pathComponent.getId()); // 输出: 0(需后续设置)