Java面向对象编程(OOP)深度解析
一、面向对象四大核心特性
1. 封装 (Encapsulation)
核心思想:隐藏实现细节,暴露安全接口
public class BankAccount {
// 私有字段(数据隐藏)
private double balance;
private String accountNumber;
// 公开方法(受控访问)
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance; // 只读访问
}
}
2. 继承 (Inheritance)
实现代码复用和层次化设计
// 父类
class Animal {
void breathe() {
System.out.println("呼吸氧气");
}
}
// 子类继承
class Dog extends Animal {
void bark() {
System.out.println("汪汪叫");
}
}
3. 多态 (Polymorphism)
同一操作作用于不同对象产生不同行为
interface Shape {
double area(); // 抽象方法
}
class Circle implements Shape {
double radius;
public double area() {
return Math.PI * radius * radius;
}
}
class Square implements Shape {
double side;
public double area() {
return side * side;
}
}
// 多态调用
public void printArea(Shape shape) {
System.out.println("面积: " + shape.area());
}
4. 抽象 (Abstraction)
提取共性,隐藏实现细节
// 抽象类
abstract class Vehicle {
abstract void move(); // 抽象方法
void startEngine() { // 具体方法
System.out.println("引擎启动");
}
}
// 具体实现
class Car extends Vehicle {
void move() {
System.out.println("公路行驶");
}
}
二、类与对象详解
1. 类组成要素
public class Person {
// 1. 字段(成员变量)
private String name;
private int age;
// 2. 构造方法(初始化对象)
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 3. 方法(行为)
public void introduce() {
System.out.println("我叫" + name + ",今年" + age + "岁");
}
// 4. 静态成员(类级别)
public static int population = 0;
// 5. 代码块(初始化逻辑)
{
System.out.println("对象创建中...");
}
}
2. 对象生命周期
// 1. 创建对象
Person p = new Person("张三", 25);
// 2. 使用对象
p.introduce();
// 3. 对象销毁(由GC管理)
p = null; // 取消引用
System.gc(); // 建议垃圾回收(非强制)
三、关键概念深度解析
1. 构造方法特殊用法
class Student {
private String name;
private int grade;
// 方法重载(Overloading)
public Student() { // 默认构造器
this("未命名", 1); // 调用其他构造器
}
public Student(String name) {
this(name, 1); // 链式调用
}
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
}
2. 访问控制权限
修饰符 | 类内 | 同包 | 子类 | 其他包 |
---|---|---|---|---|
private | ✓ | ✗ | ✗ | ✗ |
default | ✓ | ✓ | ✗ | ✗ |
protected | ✓ | ✓ | ✓ | ✗ |
public | ✓ | ✓ | ✓ | ✓ |
3. 静态与非静态对比
class Calculator {
// 实例成员(每个对象独立)
private int serialNumber;
// 静态成员(类共享)
public static final double PI = 3.1415926;
// 静态方法(不能访问实例成员)
public static int add(int a, int b) {
return a + b;
}
// 实例方法(可访问静态成员)
public double circleArea(double r) {
return PI * r * r;
}
}
四、高级面向对象特性
1. 接口进化(Java 8+)
interface SmartDevice {
// 1. 抽象方法(必须实现)
void turnOn();
// 2. 默认方法(可选重写)
default void updateFirmware() {
System.out.println("固件更新中...");
}
// 3. 静态方法(接口直接调用)
static boolean isConnected() {
return checkNetworkStatus();
}
// 4. 私有方法(Java 9+)
private static boolean checkNetworkStatus() {
// 检测逻辑
return true;
}
}
2. 抽象类 vs 接口
特性 | 抽象类 | 接口 |
---|---|---|
方法实现 | 可包含具体方法 | Java 8前只能抽象方法 |
字段 | 可包含实例字段 | 默认为public static final |
构造方法 | 可以有 | 不能有 |
多继承 | 单继承 | 多实现 |
设计目的 | 代码复用 | 定义契约 |
3. 枚举高级用法
enum Planet {
// 枚举实例(本质是对象)
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6);
// 枚举字段
private final double mass;
private final double radius;
// 枚举构造器
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
// 枚举方法
public double surfaceGravity() {
return G * mass / (radius * radius);
}
}
五、面向对象设计原则(SOLID)
-
单一职责原则 (SRP)
// 违反:同时处理用户信息和数据库操作 class UserManager { void createUser() { /* ... */ } void saveToDatabase() { /* ... */ } } // 遵循:拆分职责 class User { // 用户数据模型 } class UserRepository { void saveUser(User user) { /* 数据库操作 */ } }
-
开闭原则 (OCP)
// 抽象支付接口 interface PaymentProcessor { void processPayment(double amount); } // 具体实现(扩展开放) class CreditCardProcessor implements PaymentProcessor { public void processPayment(double amount) { /* 信用卡逻辑 */ } } class PayPalProcessor implements PaymentProcessor { public void processPayment(double amount) { /* PayPal逻辑 */ } }
-
里氏替换原则 (LSP)
class Bird { void fly() { /* 飞行实现 */ } } // 违反:企鹅不会飞 class Penguin extends Bird { void fly() { throw new UnsupportedOperationException(); } } // 遵循:重构继承体系 class FlightlessBird extends Bird { void fly() { System.out.println("行走代替飞行"); } }
-
接口隔离原则 (ISP)
// 臃肿接口 interface Worker { void work(); void eat(); void sleep(); } // 拆分专用接口 interface Workable { void work(); } interface Eatable { void eat(); }
-
依赖倒置原则 (DIP)
// 高层模块不依赖低层实现 class ReportGenerator { private DataSource dataSource; // 依赖注入 ReportGenerator(DataSource dataSource) { this.dataSource = dataSource; } void generate() { dataSource.getData(); } } interface DataSource { List<Data> getData(); }
六、设计模式实践
1. 工厂模式
class PaymentFactory {
public static PaymentProcessor createProcessor(String type) {
switch(type) {
case "credit": return new CreditCardProcessor();
case "paypal": return new PayPalProcessor();
default: throw new IllegalArgumentException();
}
}
}
// 使用
PaymentProcessor processor =
PaymentFactory.createProcessor("credit");
2. 观察者模式
class NewsPublisher {
private List<Subscriber> subscribers = new ArrayList<>();
public void subscribe(Subscriber s) {
subscribers.add(s);
}
public void publishNews(String news) {
for (Subscriber s : subscribers) {
s.receive(news); // 通知所有订阅者
}
}
}
interface Subscriber {
void receive(String message);
}
七、Java内存模型与对象
1. 对象内存结构
┌───────────────────────┐
│ 对象头 (Header) │ 包含哈希码、GC信息、锁状态等
├───────────┬───────────┤
│ 实例数据 │ 字段1 │
│ (Instance │ 字段2 │
│ Data) │ ... │
├───────────┼───────────┤
│ 对齐填充 │ │ 保证对象大小是8字节的倍数
└───────────┴───────────┘
2. 对象引用类型
// 1. 强引用(默认)
Object obj = new Object();
// 2. 软引用(内存不足时回收)
SoftReference<Object> softRef = new SoftReference<>(obj);
// 3. 弱引用(GC时立即回收)
WeakReference<Object> weakRef = new WeakReference<>(obj);
// 4. 虚引用(对象回收跟踪)
PhantomReference<Object> phantomRef =
new PhantomReference<>(obj, referenceQueue);
八、最佳实践与性能优化
-
对象创建优化
- 重用对象(享元模式)
- 避免在循环中创建对象
- 使用对象池(如数据库连接池)
-
继承使用原则
// 优先使用组合而非继承 class ElectricCar { private Car car = new Car(); // 组合 private Battery battery; void drive() { car.drive(); // 复用功能 } }
-
多态性能考量
- 虚方法表(vtable)调用有开销
- 对性能关键代码考虑
final
方法 - 使用
switch
替代多态在特定场景
-
不可变对象设计
// final类 + final字段 + 无setter 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 ImmutablePoint move(int dx, int dy) { return new ImmutablePoint(x+dx, y+dy); } }
九、Java 14+ 新特性
-
Record 类(数据载体)
public record Person(String name, int age) { // 自动生成:构造器、equals、hashCode、toString } // 使用 Person p = new Person("Alice", 30); System.out.println(p.name()); // 访问器
-
密封类(Sealed Classes)
public sealed class Shape permits Circle, Square, Rectangle { ... } public final class Circle extends Shape { ... } public non-sealed class Square extends Shape { ... }
-
模式匹配(Pattern Matching)
// instanceof 自动转型 if (obj instanceof String s) { System.out.println(s.length()); } // switch模式匹配 String description = switch (shape) { case Circle c -> "圆形, 半径=" + c.radius(); case Square s -> "正方形, 边长=" + s.side(); default -> "未知形状"; };
掌握Java面向对象编程需要深入理解其核心概念,并能在实际开发中灵活运用设计原则。随着Java版本演进,现代OOP更注重简洁性(Record)、安全性(密封类)和表达能力(模式匹配),开发者应持续关注语言新特性以编写更高效的面向对象代码。