java如何封装对象
封装对象的基本概念
封装是面向对象编程的三大特性之一,主要目的是隐藏对象的内部细节,仅对外暴露必要的接口。通过封装可以提高代码的安全性和可维护性。
使用访问修饰符
Java中通过访问修饰符实现封装:
private:仅限类内部访问protected:允许子类和同包访问public:完全公开- 默认(无修饰符):同包内可访问
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
提供Getter/Setter方法
通过公共方法控制对私有字段的访问:
- Getter方法用于获取属性值
- Setter方法用于设置属性值,可加入验证逻辑
public class Account {
private double balance;
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if(amount > 0) {
balance += amount;
}
}
}
构造方法封装
通过构造方法确保对象创建时的有效性:
public class Student {
private String id;
private String name;
public Student(String id, String name) {
if(id == null || name == null) {
throw new IllegalArgumentException("参数不能为空");
}
this.id = id;
this.name = name;
}
}
方法封装
将复杂操作封装为方法,隐藏实现细节:
public class Calculator {
public double calculateCircleArea(double radius) {
return Math.PI * radius * radius;
}
}
不可变对象封装
通过final关键字和仅提供Getter方法实现不可变对象:
public final class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
内部类封装
使用内部类隐藏实现细节:
public class Outer {
private int value;
private class Inner {
void display() {
System.out.println("Value: " + value);
}
}
}
包级封装
通过包结构组织相关类,使用默认访问修饰符限制包外访问:

package com.example.util;
class InternalHelper {
// 仅限包内访问
}






