Java 封装

封装的实现步骤、private 字段与 getter/setter、封装的收益。

Beginner
Key Points封装 = 字段私有 + 公开受控访问方法;setter 里可以校验,避免对象进入非法状态。

实现 Java 封装的步骤

Three steps: make fields private, provide getters and setters, and validate inside setters. Callers can no longer bypass the rules.

  1. Declare fields private
  2. Add public getter/setter as needed
  3. Validate inside setters
Java
public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name required");
        }
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("invalid age: " + age);
        }
        this.age = age;
    }

    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Tom");
        p.setAge(28);

        System.out.println(p.getName() + " " + p.getAge());

        try {
            p.setAge(-1);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}
Output
Tom 28
invalid age: -1

封装的收益

Encapsulation lets you refactor internals freely, validate on assignment, expose read-only fields (getter only) and compute lazily. It is the most basic discipline in OOP.

Java
public class Account {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("amount must be positive");
        }
        balance += amount;
    }

    public static void main(String[] args) {
        Account a = new Account();
        a.deposit(100);
        a.deposit(50);

        System.out.println(a.getBalance());
    }
}
Output
150.0
private is not absolute security — reflection can bypass it. It expresses "internal detail, do not depend on it", a contract for collaborators.

Friends & Partners