Java封装:修仙界的"护体罡气"
作者:会编程的吕洞宾
温馨提示:封装就像给法宝加上保护罩,既保护内部结构,又提供安全的使用方式!
什么是封装?编程中的"护体神功"
想象一下,你炼制了一件绝世法宝"诛仙剑"。你肯定不会把它的内部构造直接暴露给别人,而是提供一个"剑诀"接口,让使用者通过特定方式来操控。
这就是封装:隐藏对象的内部实现细节,只提供公共的访问方式。就像给法宝加上保护罩,既安全又易用。
封装的四大访问权限:修仙界的"门规等级"
Java提供了四种访问权限,就像修仙门派的不同权限等级:
1. public:门派广场 - 完全公开
csharp
public class ImmortalSect {
public String sectName = "蜀山派"; // 所有人都能看到
public void welcomeDisciple() { // 所有人都能调用
System.out.println("欢迎加入" + sectName);
}
}
2. protected:内门弟子 - 包内和子类可见
csharp
public class CultivationMethod {
protected String secretFormula; // 只有本包和子类能看到
protected void internalMeditation() { // 内部修炼方法
System.out.println("内门心法修炼中...");
}
}
3. 默认(包访问):本门弟子 - 同包可见
csharp
class InternalAffairs { // 默认权限,同包可见
String internalRule = "门规第十条"; // 同包可见
void manageDisciples() { // 内部管理方法
System.out.println("管理弟子事务");
}
}
4. private:密室传承 - 仅本类可见
csharp
public class SupremeSword {
private String forgingSecret = "玄铁百炼之法"; // 只有本类能看到
private int spiritualPower = 1000; // 灵力值,内部使用
private void secretForgingTechnique() { // 秘传锻造术
System.out.println("施展" + forgingSecret);
}
// 提供公共接口来使用私有功能
public void activateSword() {
if (spiritualPower > 0) {
secretForgingTechnique();
System.out.println("飞剑激活,灵力:" + spiritualPower);
}
}
}
封装的实战:炼制"智能法宝"
让我们炼制一个封装良好的法宝类:
csharp
// 一个封装良好的法宝类
public class MagicTreasure {
// 私有属性:内部状态,外部不能直接访问
private String name;
private int powerLevel;
private boolean isActivated;
private String owner;
// 构造方法:初始化内部状态
public MagicTreasure(String name, int powerLevel, String owner) {
this.name = name;
setPowerLevel(powerLevel); // 通过setter设置,进行验证
this.owner = owner;
this.isActivated = false;
}
// 公共getter方法:提供受控的读取访问
public String getName() {
return name;
}
public int getPowerLevel() {
return powerLevel;
}
public String getOwner() {
return owner;
}
// 公共setter方法:提供受控的写入访问
public void setPowerLevel(int powerLevel) {
if (powerLevel >= 0 && powerLevel <= 1000) {
this.powerLevel = powerLevel;
} else {
System.out.println("灵力值必须在0-1000之间");
}
}
public void changeOwner(String newOwner) {
if (newOwner != null && !newOwner.trim().isEmpty()) {
this.owner = newOwner;
System.out.println(name + "的新主人:" + newOwner);
}
}
// 公共业务方法:封装复杂操作
public void activate() {
if (powerLevel > 0) {
isActivated = true;
System.out.println(name + "已激活!当前灵力:" + powerLevel);
} else {
System.out.println("灵力不足,无法激活法宝");
}
}
public void deactivate() {
isActivated = false;
System.out.println(name + "已休眠");
}
public void use(int consumedPower) {
if (!isActivated) {
System.out.println("请先激活法宝");
return;
}
if (consumedPower <= powerLevel) {
powerLevel -= consumedPower;
System.out.println("使用" + name + ",消耗灵力" + consumedPower);
System.out.println("剩余灵力:" + powerLevel);
} else {
System.out.println("灵力不足!需要:" + consumedPower + ",当前:" + powerLevel);
}
}
// 私有辅助方法:内部实现细节
private void internalEnergyFlow() {
System.out.println("内部灵力运转中...");
}
private boolean checkSpiritualStability() {
return powerLevel > 100;
}
}
封装的好处:为什么需要"护体罡气"
1. 数据保护:防止"走火入魔"
arduino
// 没有封装 - 危险!
class DangerousTreasure {
public int powerLevel = 100; // 直接暴露,可能被设为负值
}
// 使用封装 - 安全!
class SafeTreasure {
private int powerLevel = 100;
public void setPowerLevel(int value) {
if (value >= 0) { // 数据验证
this.powerLevel = value;
}
}
}
2. 实现隐藏:保留"改进空间"
typescript
public class SmartPillFurnace {
// 旧版本使用数组存储
// private String[] ingredients = new String[10];
// 新版本改用List,但接口不变!
private List<String> ingredients = new ArrayList<>();
// 公共接口保持不变,内部实现可以优化
public void addIngredient(String ingredient) {
ingredients.add(ingredient);
}
public void makePill() {
// 内部实现可以完全重写,不影响使用者
System.out.println("炼制仙丹,材料数量:" + ingredients.size());
}
}
3. 模块化:便于"分工合作"
csharp
// 法宝模块 - 吕洞宾负责
public class MagicSword {
private String bladeMaterial;
private int sharpness;
// 只暴露必要的接口
public void sharpen() { /* 实现细节隐藏 */ }
public void use() { /* 使用接口 */ }
}
// 剑诀模块 - 李白负责
public class SwordTechnique {
private MagicSword sword;
public SwordTechnique(MagicSword sword) {
this.sword = sword;
}
public void performTechnique() {
sword.use(); // 只通过公共接口交互
}
}
封装的进阶技巧:修仙界的"高级心法"
1. 包封装:门派的"护山大阵"
csharp
// 在com.immortal.sect.internal包中
package com.immortal.sect.internal;
class InternalCultivation { // 包级私有,外部无法访问
void secretMethod() {
System.out.println("门派秘传心法");
}
}
public class PublicInterface {
private InternalCultivation internal = new InternalCultivation();
public void publicMethod() {
// 内部实现隐藏,只暴露安全接口
internal.secretMethod();
}
}
2. 不变性封装:炼制"本命法宝"
arduino
// 不可变对象:一旦创建就不能修改
public final class ImmortalPill {
private final String name; // final确保不可变
private final int potency; // final确保不可变
private final Date createDate; // 引用也要注意防御性拷贝
public ImmortalPill(String name, int potency) {
this.name = name;
this.potency = potency;
this.createDate = new Date(); // 防御性拷贝
}
// 只有getter,没有setter
public String getName() { return name; }
public int getPotency() { return potency; }
public Date getCreateDate() {
return new Date(createDate.getTime()); // 返回拷贝,保护原始数据
}
}
3. Builder模式:复杂的"法宝炼制流程"
arduino
// 使用Builder模式封装复杂构造过程
public class SupremeMagicItem {
private final String name;
private final int power;
private final String element;
private final boolean isBindable;
// 私有构造器,强制使用Builder
private SupremeMagicItem(Builder builder) {
this.name = builder.name;
this.power = builder.power;
this.element = builder.element;
this.isBindable = builder.isBindable;
}
// Builder内部类
public static class Builder {
private String name;
private int power;
private String element = "无";
private boolean isBindable = false;
public Builder(String name, int power) {
this.name = name;
this.power = power;
}
public Builder element(String element) {
this.element = element;
return this;
}
public Builder bindable(boolean bindable) {
this.isBindable = bindable;
return this;
}
public SupremeMagicItem build() {
return new SupremeMagicItem(this);
}
}
// 使用示例
public static void main(String[] args) {
SupremeMagicItem item = new SupremeMagicItem.Builder("轩辕剑", 999)
.element("金")
.bindable(true)
.build();
}
}
实战:完整的封装修仙系统
typescript
// 完整的封装示例:修仙账户系统
public class ImmortalAccount {
// 私有属性:核心数据
private String username;
private String password; // 加密存储
private int cultivationLevel;
private double spiritualEnergy;
private List<String> treasures;
// 构造方法封装初始化逻辑
public ImmortalAccount(String username, String password) {
setUsername(username);
setPassword(password); // 密码加密
this.cultivationLevel = 1;
this.spiritualEnergy = 100.0;
this.treasures = new ArrayList<>();
}
// 受控的setter方法
public void setUsername(String username) {
if (username != null && username.length() >= 3) {
this.username = username;
} else {
throw new IllegalArgumentException("用户名至少3个字符");
}
}
private void setPassword(String password) {
// 密码加密逻辑
this.password = encryptPassword(password);
}
// 业务方法封装复杂逻辑
public boolean login(String inputPassword) {
return encryptPassword(inputPassword).equals(password);
}
public void cultivate(int hours) {
if (hours > 0) {
double energyGain = hours * 10.0;
spiritualEnergy += energyGain;
cultivationLevel += hours / 100; // 每修炼100小时升1级
System.out.println("修炼" + hours + "小时,获得灵力:" + energyGain);
}
}
public void addTreasure(String treasure) {
if (treasure != null && !treasures.contains(treasure)) {
treasures.add(treasure);
System.out.println("获得法宝:" + treasure);
}
}
// 私有辅助方法
private String encryptPassword(String password) {
// 简单的加密演示
return "encrypted_" + password;
}
// 只读的getter方法
public String getUsername() { return username; }
public int getCultivationLevel() { return cultivationLevel; }
public double getSpiritualEnergy() { return spiritualEnergy; }
public List<String> getTreasures() {
return new ArrayList<>(treasures); // 返回拷贝,保护原始数据
}
}
吕洞宾的封装心法
记住这几条修仙要诀:
- "最小权限":给每个成员最小必要的访问权限
- "数据隐藏":私有属性,公共接口
- "防御性编程":对外部输入保持警惕
- "接口稳定":内部可以随便改,接口要保持稳定
封装就像修仙者的"护体罡气",保护内部脆弱的核心,同时提供强大的外部接口。掌握了封装,你的代码就能像修炼有成的仙人一样,外御强敌,内守本心!