Java封装实现案例
封装是面向对象编程的重要特性,主要通过以下方式实现:

核心实现方式
public class Student {
// 1. 私有属性(private修饰)
private String name;
private int age;
private String studentId;
private double score;
// 2. 公有访问方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 3. 带数据验证的setter
public void setAge(int age) {
if (age > 0 && age < 150) {
this.age = age;
} else {
System.out.println("年龄不合法");
}
}
public int getAge() {
return age;
}
// 4. 只读属性(只有getter没有setter)
public String getStudentId() {
return studentId;
}
// 5. 内部封装业务逻辑
public double getScore() {
return score;
}
public void setScore(double score) {
if (score >= 0 && score <= 100) {
this.score = score;
}
}
// 6. 封装复杂业务逻辑
public String getGrade() {
if (score >= 90) return "优秀";
else if (score >= 80) return "良好";
else if (score >= 70) return "中等";
else if (score >= 60) return "及格";
else return "不及格";
}
}
使用示例
public class Main {
public static void main(String[] args) {
Student student = new Student();
// 使用setter方法设置属性
student.setName("张三");
student.setAge(20);
student.setScore(85.5);
// 使用getter方法获取属性
System.out.println("姓名: " + student.getName());
System.out.println("年龄: " + student.getAge());
System.out.println("成绩: " + student.getScore());
System.out.println("等级: " + student.getGrade());
// 尝试设置非法年龄
student.setAge(-5); // 输出:年龄不合法
}
}
进阶封装:银行账户案例
public class BankAccount {
// 私有属性
private String accountNumber;
private double balance;
private String password;
// 构造方法
public BankAccount(String accountNumber, String password) {
this.accountNumber = accountNumber;
this.password = password;
this.balance = 0.0;
}
// 存款(封装了验证逻辑)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功,当前余额: " + balance);
} else {
System.out.println("存款金额必须大于0");
}
}
// 取款(封装了密码验证和余额检查)
public void withdraw(double amount, String inputPassword) {
if (!password.equals(inputPassword)) {
System.out.println("密码错误");
return;
}
if (amount <= 0) {
System.out.println("取款金额必须大于0");
return;
}
if (amount > balance) {
System.out.println("余额不足");
return;
}
balance -= amount;
System.out.println("取款成功,当前余额: " + balance);
}
// 只提供查询余额方法,不提供修改余额的方法
public double getBalance(String inputPassword) {
if (password.equals(inputPassword)) {
return balance;
} else {
System.out.println("密码错误");
return -1;
}
}
// 封装密码修改逻辑
public void changePassword(String oldPassword, String newPassword) {
if (password.equals(oldPassword)) {
if (newPassword.length() >= 6) {
password = newPassword;
System.out.println("密码修改成功");
} else {
System.out.println("新密码长度不能少于6位");
}
} else {
System.out.println("原密码错误");
}
}
}
封装的优点
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount("10086", "123456");
// 1. 隐藏实现细节
account.deposit(1000);
// 用户不需要知道内部如何实现
// 2. 数据保护
// account.balance = 9999999; // 编译错误,不能直接访问
// 3. 数据验证
account.withdraw(200, "123456");
// 4. 提供可控的访问接口
double balance = account.getBalance("123456");
System.out.println("余额: " + balance);
}
}
封装的最佳实践
- 属性私有化:所有实例变量使用
private - 提供getter/setter:控制访问权限
- 在setter中添加验证:确保数据合法性
- 内部实现隐藏:对外只暴露必要的接口
- 使用构造方法初始化:确保对象创建时的数据完整性
封装使得代码更加安全、易维护,是Java面向对象编程的基础。