java 如何封装
封装的概念
封装是面向对象编程的三大特性之一,它将数据和操作数据的方法绑定在一起,对外隐藏内部实现细节,仅暴露必要的接口。封装能提高代码安全性、可维护性和复用性。
实现封装的关键步骤
使用访问修饰符控制可见性
private:仅当前类内部可见,外部无法直接访问。protected:当前类及其子类可见。default(默认):同一包内可见。public:全局可见。
public class Person {
private String name; // 私有属性
private int age;
// 公开的getter方法
public String getName() {
return name;
}
// 公开的setter方法
public void setName(String name) {
this.name = name;
}
}
提供公共方法访问私有属性 通过getter和setter方法间接访问私有字段,可在方法中添加逻辑控制:
public void setAge(int age) {
if (age > 0 && age < 150) { // 数据校验
this.age = age;
} else {
throw new IllegalArgumentException("Invalid age");
}
}
隐藏实现细节 将复杂逻辑封装在方法内部,调用者只需关注输入输出:
public class BankAccount {
private double balance;
public void deposit(double amount) {
// 内部可能包含日志记录、事务处理等
balance += amount;
}
}
封装的进阶实践
使用不可变对象 通过final关键字和仅提供getter方法实现:
public final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
Builder模式封装复杂对象 适用于多参数的复杂对象构造:
public class Computer {
private final String CPU;
private final String RAM;
private Computer(Builder builder) {
this.CPU = builder.CPU;
this.RAM = builder.RAM;
}
public static class Builder {
private String CPU;
private String RAM;
public Builder setCPU(String CPU) {
this.CPU = CPU;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
封装的设计原则
- 单一职责原则:每个类只负责一个明确的功能
- 迪米特法则:减少类之间的直接依赖
- 接口隔离原则:定义专用的细粒度接口
通过合理运用封装技术,可以构建出高内聚、低耦合的健壮系统架构。







