Java封装

1. 封装的原则

  • 数据隐藏: 不允许外部直接访问对象的内部数据。数据和方法通过“公共接口”与外部交互。
  • 提高安全性: 通过控制数据的访问权限,避免直接修改内部状态,确保数据的完整性。
  • 简化复杂性: 外部只需要关心如何调用方法,而不需要了解内部的复杂实现。

2. 具体讲解

  • 封装的实现方法:

    • 将类的属性(字段)设置为private,防止外部直接访问。
    • 提供公共的gettersetter方法,用于访问和修改私有属性。
  • 示例:银行账户(封装的应用)

    • 我们定义一个BankAccount类,拥有私有的账户余额(balance)和一些公共的方法来访问和修改余额。
    • 外部代码不能直接修改余额,而是必须通过类提供的depositwithdraw方法来操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class BankAccount {
// 私有属性
private double balance;

// 公共的构造方法
public BankAccount(double initialBalance) {
if (initialBalance >= 0) {
this.balance = initialBalance;
} else {
System.out.println("Initial balance cannot be negative");
}
}

// 公共方法:获取余额
public double getBalance() {
return balance;
}

// 公共方法:存款
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit amount must be positive");
}
}

// 公共方法:取款
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Invalid withdrawal amount");
}
}
}

public class Main {
public static void main(String[] args) {
// 创建银行账户对象
BankAccount account = new BankAccount(1000);

// 操作账户
account.deposit(500); // 存款500
account.withdraw(200); // 取款200

// 获取余额
System.out.println("Current balance: " + account.getBalance());
}
}

3. 总结

  • 封装的核心思想是隐藏实现细节,只通过公共接口与外界进行交互。这样做不仅能保证数据的安全性,还使得代码更易于维护,因为你可以修改内部实现而不影响外部使用它的代码。