开篇概览:面向对象的核心体系
面向对象编程(Object-Oriented Programming, OOP)是 Java 语言的核心范式,它通过对象来组织代码,模拟现实世界中的实体与行为。Java 的 OOP 体系包含三个层次:
- 核心概念:类(Class)、对象(Object)、封装(Encapsulation)——构成 OOP 的基本单元;
- 核心特性(三大特性):封装、继承(Inheritance)、多态(Polymorphism)——实现代码复用与扩展的基石;
- 高级类特性:抽象类(Abstract Class)、接口(Interface)、内部类(Inner Class)、静态成员(static)、final 修饰符等——提升设计灵活性与安全性。
掌握这些内容,不仅能写出结构清晰的代码,更能理解 Spring、Hibernate 等主流框架的设计思想。
一、面向对象核心概念
1.1 类(Class)与对象(Object)
- 类:对象的模板或蓝图,定义了对象的属性(字段)和行为(方法);
- 对象:类的实例,具有具体的状态和行为。
示例:定义类与创建对象
// 中文注释:定义一个“学生”类,包含姓名和年龄属性,以及学习行为
public class Student {
// 字段(属性)
private String name; // 学生姓名
private int age; // 学生年龄
// 构造方法:用于创建对象时初始化属性
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 方法(行为)
public void study() {
System.out.println(this.name + " 正在认真学习 Java 面向对象编程!");
}
// Getter 方法:提供安全的属性访问
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
// 测试类
public class OOPDemo {
public static void main(String[] args) {
// 创建 Student 类的对象(实例)
Student student1 = new Student("张三", 20);
Student student2 = new Student("李四", 22);
// 调用对象的方法
student1.study(); // 输出:张三 正在认真学习 Java 面向对象编程!
student2.study(); // 输出:李四 正在认真学习 Java 面向对象编程!
// 访问对象的属性(通过 getter)
System.out.println(student1.getName() + " 的年龄是 " + student1.getAge() + " 岁。");
}
}
✅ 关键点:
new Student(...)创建对象,调用构造方法;this指向当前对象实例;- 属性私有化 + 公共 getter/setter 是封装的体现。
1.2 封装(Encapsulation)
封装是将对象的内部状态(字段)隐藏起来,只通过公共方法(接口) 与外界交互,从而保护数据安全、提高代码可维护性。
封装的实现方式:
- 使用
private修饰字段; - 提供
public的 getter/setter 方法; - 在 setter 中加入校验逻辑。
示例:带数据校验的封装
public class BankAccount {
private String accountNumber; // 账号(私有)
private double balance; // 余额(私有)
public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance >= 0 ? initialBalance : 0;
}
// 取款方法:封装业务逻辑
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("成功取出 " + amount + " 元,当前余额:" + balance);
return true;
} else {
System.out.println("取款失败:余额不足或金额无效!");
return false;
}
}
// 存款方法
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("成功存入 " + amount + " 元,当前余额:" + balance);
} else {
System.out.println("存款金额必须大于0!");
}
}
// 只读访问余额(不提供 setter)
public double getBalance() {
return balance;
}
public String getAccountNumber() {
return accountNumber;
}
}
// 测试封装
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount("6222****1234", 1000);
account.withdraw(500); // 成功
account.withdraw(600); // 失败:余额不足
// account.balance = -1000; // ❌ 编译错误:balance 是 private 的!
System.out.println("账户余额:" + account.getBalance());
}
}
✅ 封装的好处:
- 防止非法数据(如负余额);
- 修改内部实现不影响外部调用;
- 提高代码健壮性与安全性。
二、面向对象三大核心特性
2.1 继承(Inheritance)
继承允许一个类(子类)复用另一个类(父类)的字段和方法,并可扩展或重写行为。
- 关键字:
extends - Java 支持单继承(一个类只能有一个直接父类)
- 所有类默认继承
java.lang.Object
示例:继承与方法重写
// 父类:动物
class Animal {
protected String name; // 使用 protected 允许子类访问
public Animal(String name) {
this.name = name;
}
// 通用行为
public void eat() {
System.out.println(name + " 正在吃东西。");
}
// 可被子类重写的方法
public void makeSound() {
System.out.println(name + " 发出声音。");
}
}
// 子类:狗
class Dog extends Animal {
public Dog(String name) {
super(name); // 调用父类构造方法
}
// 重写父类方法
@Override
public void makeSound() {
System.out.println(name + " 汪汪叫!");
}
// 子类特有方法
public void wagTail() {
System.out.println(name + " 摇尾巴表示开心!");
}
}
// 子类:猫
class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(name + " 喵喵叫!");
}
}
// 测试继承
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog("旺财");
Cat cat = new Cat("咪咪");
dog.eat(); // 继承自 Animal
dog.makeSound(); // 重写后的方法
dog.wagTail(); // Dog 特有方法
cat.eat();
cat.makeSound();
}
}
✅ 继承要点:
super()必须在子类构造方法第一行;@Override注解确保正确重写;protected成员对子类可见。
2.2 多态(Polymorphism)
多态指同一个引用变量,调用同一个方法,在运行时表现出不同行为。它是 OOP 最强大的特性,实现“编译时绑定,运行时决定”。
多态的实现条件:
- 有继承或实现关系;
- 子类重写父类方法;
- 父类引用指向子类对象。
示例:多态的应用
// 使用上文的 Animal、Dog、Cat 类
public class PolymorphismDemo {
public static void main(String[] args) {
// 父类引用指向子类对象(多态)
Animal animal1 = new Dog("小黑");
Animal animal2 = new Cat("小白");
// 调用相同方法,实际执行子类重写后的方法
animal1.makeSound(); // 输出:小黑 汪汪叫!
animal2.makeSound(); // 输出:小白 喵喵叫!
// 调用父类方法
animal1.eat(); // 输出:小黑 正在吃东西。
// ❌ 不能调用子类特有方法(编译错误)
// animal1.wagTail(); // 编译失败:Animal 类没有 wagTail 方法
// 若需调用,需向下转型(不推荐滥用)
if (animal1 instanceof Dog) {
Dog dog = (Dog) animal1;
dog.wagTail(); // 安全转型后调用
}
}
// 多态在方法参数中的应用
public static void letAnimalMakeSound(Animal animal) {
animal.makeSound(); // 运行时决定调用哪个子类的方法
}
}
✅ 多态的优势:
- 提高代码扩展性:新增子类无需修改现有逻辑;
- 降低耦合度:方法只依赖父类接口;
- 实现“开闭原则”(对扩展开放,对修改关闭)。
三、高级类特性
3.1 抽象类(Abstract Class)
- 使用
abstract关键字定义; - 可包含抽象方法(无方法体,子类必须实现)和具体方法;
- 不能被实例化,只能被继承;
- 适用于“部分实现 + 强制规范”的场景。
示例:抽象类定义模板
// 中文注释:定义一个“图形”抽象类,要求所有子类必须实现计算面积的方法
abstract class Shape {
protected String color;
public Shape(String color) {
this.color = color;
}
// 具体方法:所有图形都有颜色
public void displayColor() {
System.out.println("图形颜色:" + color);
}
// 抽象方法:子类必须实现
public abstract double calculateArea();
}
// 圆形类
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// 矩形类
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(String color, double width, double height) {
super(color);
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
}
// 测试抽象类
public class AbstractClassDemo {
public static void main(String[] args) {
Shape circle = new Circle("红色", 5.0);
Shape rectangle = new Rectangle("蓝色", 4.0, 6.0);
circle.displayColor();
System.out.println("圆形面积:" + circle.calculateArea());
rectangle.displayColor();
System.out.println("矩形面积:" + rectangle.calculateArea());
// Shape shape = new Shape("绿色"); // ❌ 编译错误:抽象类不能实例化
}
}
3.2 接口(Interface)
- 使用
interface关键字定义; - Java 8+ 支持:
- 默认方法(
default) - 静态方法(
static) - 私有方法(
private,Java 9+)
- 默认方法(
- 类通过
implements实现接口; - 支持多实现(弥补单继承限制);
- 适用于“行为契约”场景。
示例:接口定义能力
// 中文注释:定义“可飞行”接口,描述飞行能力
interface Flyable {
// 抽象方法(默认 public abstract)
void fly();
// 默认方法:提供通用实现
default void land() {
System.out.println("安全着陆!");
}
// 静态方法
static void describe() {
System.out.println("Flyable 接口表示具备飞行能力。");
}
}
// 鸟类实现 Flyable
class Bird implements Flyable {
private String name;
public Bird(String name) {
this.name = name;
}
@Override
public void fly() {
System.out.println(name + " 展翅高飞!");
}
}
// 飞机类也实现 Flyable
class Airplane implements Flyable {
@Override
public void fly() {
System.out.println("飞机启动引擎,冲上云霄!");
}
}
// 测试接口
public class InterfaceDemo {
public static void main(String[] args) {
Flyable bird = new Bird("老鹰");
Flyable plane = new Airplane();
bird.fly(); // 老鹰 展翅高飞!
plane.fly(); // 飞机启动引擎,冲上云霄!
bird.land(); // 调用默认方法:安全着陆!
Flyable.describe(); // 调用静态方法
// 多态:接口引用指向实现类对象
makeItFly(bird);
makeItFly(plane);
}
// 方法参数为接口类型,体现多态
public static void makeItFly(Flyable f) {
f.fly();
}
}
✅ 接口 vs 抽象类:
特性 接口 抽象类 关键字 interfaceabstract class继承/实现 implements(多实现)extends(单继承)方法 抽象 + 默认 + 静态 抽象 + 具体 字段 public static final任意访问修饰符 设计目的 能做什么(行为契约) 是什么(is-a 关系)
3.3 其他高级特性
(1)static 静态成员
- 属于类,不属于对象;
- 通过类名直接访问;
- 常用于工具方法、常量。
class MathUtils {
public static final double PI = 3.14159;
public static int add(int a, int b) {
return a + b;
}
}
// 使用
System.out.println(MathUtils.PI);
System.out.println(MathUtils.add(3, 5));
(2)final 修饰符
final class:不能被继承(如String);final method:不能被重写;final variable:常量(引用不可变)。
final class UtilityClass {
public final void printMessage() {
System.out.println("此方法不能被重写");
}
}
(3)内部类(Inner Class)
- 成员内部类、静态内部类、局部内部类、匿名内部类;
- 常用于事件监听、适配器模式等。
class Outer {
private String msg = "外部类消息";
class Inner {
public void display() {
System.out.println(msg); // 可访问外部类私有成员
}
}
}
// 使用
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
总结
| 层级 | 内容 | 核心价值 |
|---|---|---|
| 核心概念 | 类、对象、封装 | 构建程序的基本单元,保护数据安全 |
| 三大特性 | 封装、继承、多态 | 实现代码复用、扩展与灵活设计 |
| 高级特性 | 抽象类、接口、static、final、内部类 | 提升架构设计能力,支持复杂业务场景 |
📌 最佳实践建议:
- 优先使用组合而非继承(避免继承层次过深);
- 接口用于定义能力,抽象类用于定义共性;
- 多态是解耦的关键,广泛应用于框架设计(如 Spring 的 Bean 管理);
- 封装是安全的第一道防线,不要暴露内部状态。
掌握这些面向对象的核心思想与语法,你将具备构建高内聚、低耦合、易维护 Java 系统的能力。
详解&spm=1001.2101.3001.5002&articleId=152409032&d=1&t=3&u=9144bf6520504c6aa4ded0b613dbbd87)
535

被折叠的 条评论
为什么被折叠?



