本文目录导读:

我来为你提供几个内部类的完整案例,从基础到进阶:
案例1:成员内部类 - 图书管理系统
import java.util.ArrayList;
import java.util.List;
/**
* 成员内部类案例:模拟图书管理系统
* 外部类:书店(BookStore)
* 内部类:图书信息(BookInfo)
*/
public class BookStore {
private String storeName;
private List<BookInfo> books;
// 构造函数
public BookStore(String storeName) {
this.storeName = storeName;
this.books = new ArrayList<>();
System.out.println("创建了书店:" + storeName);
}
/**
* 成员内部类 - 图书信息
* 可以访问外部类的所有成员(包括私有成员)
*/
public class BookInfo {
private String bookName;
private double price;
private String author;
public BookInfo(String bookName, double price, String author) {
this.bookName = bookName;
this.price = price;
this.author = author;
}
// 内部类方法可以访问外部类成员
public void display() {
System.out.println("书店:" + storeName); // 访问外部类成员
System.out.println("书名:" + bookName);
System.out.println("价格:¥" + price);
System.out.println("作者:" + author);
System.out.println("------------------------");
}
// 获取外部类引用
public BookStore getOuter() {
return BookStore.this;
}
}
// 添加图书
public void addBook(String name, double price, String author) {
BookInfo book = new BookInfo(name, price, author);
books.add(book);
System.out.println("添加图书成功:" + name);
}
// 显示所有图书
public void showAllBooks() {
System.out.println("\n=== " + storeName + " 的所有图书 ===");
for (BookInfo book : books) {
book.display();
}
}
public static void main(String[] args) {
// 创建书店
BookStore store = new BookStore("新华书店");
// 方式一:通过外部类方法添加图书
store.addBook("Java编程思想", 89.5, "Bruce Eckel");
store.addBook("深入理解Java虚拟机", 129.0, "周志明");
// 方式二:直接创建内部类实例
BookStore.BookInfo book = store.new BookInfo("设计模式", 76.8, "GoF");
book.display();
// 显示所有图书
store.showAllBooks();
}
}
案例2:静态内部类 - 计算器
/**
* 静态内部类案例:多功能计算器
* 外部类:Calculator
* 静态内部类:Operation(操作类型)
*/
public class Calculator {
private double result = 0;
/**
* 静态内部类 - 模拟数学运算
* 静态内部类只能访问外部类的静态成员
*/
public static class MathOperations {
// 静态方法:加法
public static double add(double a, double b) {
return a + b;
}
// 静态方法:减法
public static double subtract(double a, double b) {
return a - b;
}
// 静态方法:乘法
public static double multiply(double a, double b) {
return a * b;
}
// 静态方法:除法(带异常处理)
public static double divide(double a, double b) throws IllegalArgumentException {
if (b == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return a / b;
}
// 非静态方法:平方
public double square(double a) {
return a * a;
}
// 内部方法:描述运算
public void describeOperation() {
System.out.println("这是计算器的数学运算功能");
}
}
// 实例方法:执行运算
public void calculate() {
// 直接使用静态内部类
double sum = MathOperations.add(10, 5);
System.out.println("10 + 5 = " + sum);
double diff = MathOperations.subtract(10, 5);
System.out.println("10 - 5 = " + diff);
double product = MathOperations.multiply(10, 5);
System.out.println("10 * 5 = " + product);
try {
double quotient = MathOperations.divide(10, 5);
System.out.println("10 / 5 = " + quotient);
} catch (IllegalArgumentException e) {
System.out.println("计算错误:" + e.getMessage());
}
// 创建静态内部类实例(不需要外部类实例)
MathOperations ops = new MathOperations();
double squared = ops.square(5);
System.out.println("5 的平方 = " + squared);
ops.describeOperation();
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.calculate();
// 可以直接调用静态内部类的静态方法
double result = Calculator.MathOperations.add(100, 200);
System.out.println("\n直接调用静态方法:100 + 200 = " + result);
}
}
案例3:局部内部类 - 学生管理系统
import java.util.ArrayList;
import java.util.List;
/**
* 局部内部类案例:学生成绩管理系统
* 局部内部类定义在方法内部,只能在方法内使用
*/
public class StudentManager {
private List<String> studentNames = new ArrayList<>();
public StudentManager() {
studentNames.add("张三");
studentNames.add("李四");
studentNames.add("王五");
studentNames.add("赵六");
}
/**
* 查询学生信息 - 使用局部内部类
*/
public void searchStudent(String keyword) {
// 局部内部类(在方法内部定义)
class StudentInfo {
private String name;
private int score;
public StudentInfo(String name, int score) {
this.name = name;
this.score = score;
}
public void display() {
System.out.println("学生:" + name);
System.out.println("成绩:" + score);
System.out.println("-----------------");
}
// 局部内部类可以访问外部类的成员和方法参数
public void validate() {
if (studentNames.contains(keyword)) { // 访问方法的参数
System.out.println(keyword + " 存在");
} else {
System.out.println(keyword + " 不存在");
}
}
}
// 在方法内创建局部内部类实例
StudentInfo student1 = new StudentInfo("张三", 85);
StudentInfo student2 = new StudentInfo("李四", 92);
System.out.println("\n=== 搜索关键词:" + keyword + " ===");
// 显示学生信息
student1.display();
student2.display();
// 验证学生是否存在
student1.validate();
// 遍历外部类成员
System.out.println(groupStudents());
}
/**
* 分组学生 - 返回类型为局部内部类的父接口
* 使用局部内部类实现分组逻辑
*/
public List<List<String>> groupStudents() {
// 局部内部类实现分组功能
class Group {
private List<String> groupA = new ArrayList<>();
private List<String> groupB = new ArrayList<>();
public void addToGroup(String name, boolean isGroupA) {
if (isGroupA) {
groupA.add(name);
} else {
groupB.add(name);
}
}
public List<List<String>> getGroups() {
List<List<String>> result = new ArrayList<>();
result.add(groupA);
result.add(groupB);
return result;
}
}
Group group = new Group();
for (int i = 0; i < studentNames.size(); i++) {
if (i % 2 == 0) {
group.addToGroup(studentNames.get(i), true);
} else {
group.addToGroup(studentNames.get(i), false);
}
}
return group.getGroups();
}
public static void main(String[] args) {
StudentManager manager = new StudentManager();
manager.searchStudent("张三");
}
}
案例4:匿名内部类 - 事件处理
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* 匿名内部类案例:GUI事件处理
* 匿名内部类是没有类名的内部类,主要用于实现接口或继承抽象类
*/
public class AnonymousClassDemo {
// 接口定义
interface Greeting {
void sayHello();
}
// 抽象类定义
abstract static class Animal {
abstract void makeSound();
void eat() {
System.out.println("动物在吃东西");
}
}
// 普通类
static class MyButton {
private String text;
private ActionListener listener;
public MyButton(String text) {
this.text = text;
}
public void setActionListener(ActionListener listener) {
this.listener = listener;
}
public void click() {
System.out.println("点击按钮:" + text);
if (listener != null) {
listener.actionPerformed(new ActionEvent(this, 1, "click"));
}
}
}
public static void main(String[] args) {
// 1. 匿名内部类实现接口
Greeting greeting = new Greeting() {
@Override
public void sayHello() {
System.out.println("你好,来自匿名内部类!");
}
};
greeting.sayHello();
// 2. 匿名内部类继承抽象类
Animal dog = new Animal() {
@Override
void makeSound() {
System.out.println("汪汪汪!");
}
// 可以添加新方法(但无法从外部调用)
void wagTail() {
System.out.println("摇尾巴");
}
};
dog.makeSound();
dog.eat();
// 3. 匿名内部类作为事件监听器
MyButton myButton = new MyButton("提交");
myButton.setActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了!");
System.out.println("事件来源:" + e.getSource());
System.out.println("事件命令:" + e.getActionCommand());
}
});
myButton.click();
// 4. 匿名内部类实现Runnable接口(多线程)
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println("子线程执行中:" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
// 5. 使用Lambda表达式(Java 8+ 替代匿名内部类)
Runnable runnable = () -> System.out.println("Lambda表达式实现Runnable");
runnable.run();
}
}
案例5:综合应用 - 电话簿管理系统
import java.util.ArrayList;
import java.util.List;
/**
* 综合案例:电话簿管理器
* 演示各种类型的内部类使用
*/
public class PhoneBook {
// 静态内部类:联系人类型枚举
public static class ContactType {
public static final String FAMILY = "家庭";
public static final String FRIEND = "朋友";
public static final String WORK = "工作";
public static final String OTHER = "其他";
}
private List<Contact> contacts;
private String ownerName;
public PhoneBook(String ownerName) {
this.ownerName = ownerName;
this.contacts = new ArrayList<>();
}
// 成员内部类:联系人信息
public class Contact {
private String name;
private String phone;
private String email;
private String type;
public Contact(String name, String phone, String email, String type) {
this.name = name;
this.phone = phone;
this.email = email;
this.type = type;
}
public void display() {
System.out.println("姓名:" + name);
System.out.println("电话:" + phone);
System.out.println("邮箱:" + email);
System.out.println("类型:" + type);
System.out.println("------------------------");
}
public String getName() {
return name;
}
public String getType() {
return type;
}
}
// 添加联系人
public void addContact(String name, String phone, String email, String type) {
Contact contact = new Contact(name, phone, email, type);
contacts.add(contact);
System.out.println("添加联系人成功:" + name);
}
// 搜索联系人 - 使用局部内部类
public void searchContacts(String keyword) {
class SearchResult {
private List<Contact> results = new ArrayList<>();
public void search() {
for (Contact c : contacts) {
if (c.getName().contains(keyword) || c.getType().contains(keyword)) {
results.add(c);
}
}
}
public void display() {
if (results.isEmpty()) {
System.out.println("没有找到匹配的联系人");
return;
}
System.out.println("找到 " + results.size() + " 个联系人:");
for (Contact c : results) {
c.display();
}
}
}
SearchResult result = new SearchResult();
result.search();
System.out.println("\n=== 搜索结果(关键词:" + keyword + ")===");
result.display();
}
// 按类型分组 - 使用匿名内部类
public void groupByType() {
// 使用匿名内部类创建分组器
GroupBy<String, Contact> groupBy = new GroupBy<String, Contact>() {
@Override
public String getKey(Contact item) {
return item.getType();
}
@Override
public List<String> getGroups() {
List<String> types = new ArrayList<>();
types.add(ContactType.FAMILY);
types.add(ContactType.FRIEND);
types.add(ContactType.WORK);
types.add(ContactType.OTHER);
return types;
}
};
System.out.println("\n=== 按类型分组联系人 ===");
for (String type : groupBy.getGroups()) {
System.out.println("\n" + type + "联系人:");
for (Contact c : contacts) {
if (c.getType().equals(type)) {
c.display();
}
}
}
}
// 内部类接口定义
interface GroupBy<K, V> {
K getKey(V item);
List<K> getGroups();
}
public static void main(String[] args) {
PhoneBook phoneBook = new PhoneBook("张三");
// 添加联系人
phoneBook.addContact("爸爸", "13812345678", "father@email.com", ContactType.FAMILY);
phoneBook.addContact("妈妈", "13912345678", "mother@email.com", ContactType.FAMILY);
phoneBook.addContact("小明", "13612345678", "xiaoming@email.com", ContactType.FRIEND);
phoneBook.addContact("李经理", "13512345678", "manager@email.com", ContactType.WORK);
phoneBook.addContact("王医生", "13712345678", "doctor@email.com", ContactType.OTHER);
// 搜索联系人
phoneBook.searchContacts("家庭");
// 按类型分组
phoneBook.groupByType();
}
}
内部类特性总结表
| 类型 | 定义位置 | 访问外部类成员 | 创建方式 | 使用场景 |
|---|---|---|---|---|
| 成员内部类 | 类体内 | 可以访问所有成员 | 外部类实例.new | 需要访问外部类实例时 |
| 静态内部类 | 类体内(static) | 只能访问静态成员 | new 外部类.内部类 | 与外部类实例无关 |
| 局部内部类 | 方法内 | 可以访问final变量 | 在方法内new | 局部使用 |
| 匿名内部类 | 方法内 | 可以访问final变量 | new 接口/抽象类 | 一次性使用 |
关键注意事项
-
成员内部类:
- 可以访问外部类所有成员(包括私有)
- 内部类持有外部类的引用
-
静态内部类:
- 只能访问外部类的静态成员
- 不持有外部类引用
- 创建不需要外部类实例
-
局部内部类:
- 定义在方法内
- 只能访问final或effectively final的局部变量
- 作用范围仅限方法内
-
匿名内部类:
- 没有类名
- 必须继承一个类或实现一个接口
- 不能定义构造函数
- 通常用于一次性使用的场景
这些案例覆盖了内部类的所有类型,展示了它们在实际开发中的应用场景。