java 如何封装类
封装类的核心原则
封装是面向对象编程的三大特性之一,通过隐藏对象内部细节和提供公共访问方法,增强代码安全性和可维护性。Java中主要通过访问修饰符和规范化方法实现。
使用访问修饰符控制可见性
-
private:限制成员仅能在当前类内访问,彻底隐藏实现细节。例如私有字段和内部辅助方法:
private String name; private void validateInput() { ... } -
protected:允许子类和同包类访问,适用于需要继承扩展的场景:
protected int calculateInternal() { ... } -
public:对外暴露的接口方法,需保持稳定:
public String getName() { return this.name; }
规范化方法命名
-
获取私有字段值使用
get前缀(Getter):public int getAge() { return this.age; } -
修改私有字段值使用
set前缀(Setter),可加入验证逻辑:public void setName(String name) { if(name != null) { this.name = name; } }
构造方法封装
-
通过构造方法强制初始化必要属性:
public Student(String id, String name) { this.id = id; this.name = name; } -
重载构造方法提供不同初始化方式:
public Student(String id) { this(id, "Anonymous"); }
不可变类设计
-
字段声明为
final并移除Setter方法:public final class ImmutablePoint { private final int x; private final int y; public ImmutablePoint(int x, int y) { this.x = x; this.y = y; } // 只有Getter没有Setter }
业务逻辑封装
-
将相关操作封装为独立方法,而非直接暴露字段:
public class BankAccount { private double balance; public void deposit(double amount) { if(amount > 0) balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount > balance) throw new InsufficientFundsException(); balance -= amount; } }
静态工厂方法
-
使用静态方法替代构造方法,提高灵活性和可读性:
public class Complex { private final double real; private final double imaginary; private Complex(double r, double i) { real = r; imaginary = i; } public static Complex fromCartesian(double r, double i) { return new Complex(r, i); } public static Complex fromPolar(double modulus, double angle) { return new Complex(modulus*Math.cos(angle), modulus*Math.sin(angle)); } }
内部类封装
-
使用内部类隐藏仅对当前类有用的实现细节:
public class Outer { private String secret; private class Inner { void accessSecret() { System.out.println(secret); // 可访问外部类私有成员 } } }
包级封装
- 无修饰符(默认)实现包内可见性,控制跨包访问:
class PackagePrivateClass { // 仅同包可见 void packagePrivateMethod() { ... } }
通过以上方式实现的封装,能够有效隔离变化、降低耦合度,同时保证对象的完整性和安全性。实际开发中应根据业务需求选择适当的封装粒度,过度封装可能导致代码冗余,而封装不足则会降低代码健壮性。







