匿名内部类案例

wen java案例 1

本文目录导读:

匿名内部类案例

  1. 案例1:基础用法 - 接口实现
  2. 案例2:继承抽象类
  3. 案例3:Comparator排序
  4. 案例4:事件监听器
  5. 案例5:多线程实现
  6. 案例6:策略模式实现
  7. 案例7:实际业务场景
  8. 匿名内部类特点总结

我来为你提供几个匿名内部类的典型案例,从基础到进阶逐步展示其用法。

案例1:基础用法 - 接口实现

// 定义一个接口
interface Greeting {
    void sayHello();
    void sayGoodbye();
}
public class BasicAnonymous {
    public static void main(String[] args) {
        // 使用匿名内部类实现接口
        Greeting greeting = new Greeting() {
            @Override
            public void sayHello() {
                System.out.println("你好!");
            }
            @Override
            public void sayGoodbye() {
                System.out.println("再见!");
            }
        };
        greeting.sayHello();
        greeting.sayGoodbye();
        // 另一个匿名内部类实例
        Greeting englishGreeting = new Greeting() {
            @Override
            public void sayHello() {
                System.out.println("Hello!");
            }
            @Override
            public void sayGoodbye() {
                System.out.println("Goodbye!");
            }
        };
        englishGreeting.sayHello();
        englishGreeting.sayGoodbye();
    }
}

案例2:继承抽象类

// 抽象类
abstract class Animal {
    abstract void makeSound();
    void eat() {
        System.out.println("动物在吃东西...");
    }
}
public class AbstractAnonymous {
    public static void main(String[] args) {
        // 使用匿名内部类创建不同动物的实例
        Animal dog = new Animal() {
            @Override
            void makeSound() {
                System.out.println("汪汪汪!");
            }
            @Override
            void eat() {
                System.out.println("狗在啃骨头...");
            }
        };
        Animal cat = new Animal() {
            @Override
            void makeSound() {
                System.out.println("喵喵喵!");
            }
            // 使用默认的eat方法
        };
        dog.makeSound();
        dog.eat();
        cat.makeSound();
        cat.eat(); // 调用默认实现
    }
}

案例3:Comparator排序

import java.util.*;
public class ComparatorAnonymous {
    public static void main(String[] args) {
        // 创建Person列表
        List<Person> people = Arrays.asList(
            new Person("张三", 25),
            new Person("李四", 20),
            new Person("王五", 30)
        );
        // 按年龄排序 - 使用匿名内部类
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return Integer.compare(p1.getAge(), p2.getAge());
            }
        });
        System.out.println("按年龄排序:");
        for (Person p : people) {
            System.out.println(p);
        }
        // 按姓名排序 - 另一个匿名内部类实例
        Collections.sort(people, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                return p1.getName().compareTo(p2.getName());
            }
        });
        System.out.println("\n按姓名排序:");
        for (Person p : people) {
            System.out.println(p);
        }
    }
}
class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() { return name; }
    public int getAge() { return age; }
    @Override
    public String toString() {
        return name + " (" + age + "岁)";
    }
}

案例4:事件监听器

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EventListenerExample {
    public static void main(String[] args) {
        // 创建窗口
        JFrame frame = new JFrame("按钮事件示例");
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());
        // 创建按钮
        JButton button = new JButton("点击我");
        // 使用匿名内部类添加动作监听器
        button.addActionListener(new ActionListener() {
            private int clickCount = 0; // 可以定义成员变量
            @Override
            public void actionPerformed(ActionEvent e) {
                clickCount++;
                System.out.println("按钮被点击了 " + clickCount + " 次!");
                // 修改按钮文本 - 可以访问外部变量
                button.setText("已点击" + clickCount + "次");
            }
        });
        // 添加鼠标监听器(另一个匿名内部类)
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                button.setBackground(Color.YELLOW);
            }
            @Override
            public void mouseExited(MouseEvent e) {
                button.setBackground(Color.LIGHT_GRAY);
            }
        });
        frame.add(button);
        frame.setVisible(true);
    }
}

案例5:多线程实现

public class ThreadAnonymous {
    public static void main(String[] args) {
        // 使用匿名内部类实现Runnable接口
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.println("线程1: 正在处理第" + i + "个任务");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        // 另一个匿名内部类创建线程
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 5; i++) {
                    System.out.println("线程2: 正在处理第" + i + "个任务");
                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.out.println("启动多线程...");
        thread1.start();
        thread2.start();
        // 使用匿名内部类继承Thread类
        Thread thread3 = new Thread() {
            @Override
            public void run() {
                System.out.println("线程3正在执行");
            }
        };
        thread3.start();
    }
}

案例6:策略模式实现

import java.util.function.Function;
public class StrategyPattern {
    // 定义一个策略接口
    interface PaymentStrategy {
        void pay(double amount);
    }
    public static void main(String[] args) {
        // 使用匿名内部类实现不同的支付策略
        PaymentStrategy creditCard = new PaymentStrategy() {
            @Override
            public void pay(double amount) {
                System.out.printf("使用信用卡支付:¥%.2f\n", amount);
                System.out.println("信用卡支付成功,获得积分奖励");
            }
        };
        PaymentStrategy wechatPay = new PaymentStrategy() {
            @Override
            public void pay(double amount) {
                System.out.printf("使用微信支付:¥%.2f\n", amount);
                System.out.println("微信支付成功,享受随机立减优惠");
            }
        };
        PaymentStrategy alipay = new PaymentStrategy() {
            @Override
            public void pay(double amount) {
                System.out.printf("使用支付宝支付:¥%.2f\n", amount);
                System.out.println("支付宝支付成功,获得花呗积分");
            }
        };
        // 执行支付
        System.out.println("=== 演示不同的支付方式 ===");
        creditCard.pay(100.0);
        System.out.println();
        wechatPay.pay(250.0);
        System.out.println();
        alipay.pay(88.8);
    }
}

案例7:实际业务场景

import java.util.*;
public class BusinessExample {
    // 定义一个数据处理器
    interface DataProcessor {
        Map<String, Object> process(List<Map<String, Object>> data);
    }
    public static void main(String[] args) {
        // 模拟用户数据
        List<Map<String, Object>> users = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            Map<String, Object> user = new HashMap<>();
            user.put("id", i);
            user.put("name", "用户" + i);
            user.put("score", 60 + i * 7);
            users.add(user);
        }
        // 处理用户数据:计算平均分和最高分
        DataProcessor scoreAnalyzer = new DataProcessor() {
            @Override
            public Map<String, Object> process(List<Map<String, Object>> data) {
                Map<String, Object> result = new HashMap<>();
                double total = 0;
                int max = 0;
                String topUser = "";
                int count = 0;
                for (Map<String, Object> user : data) {
                    int score = (int) user.get("score");
                    total += score;
                    count++;
                    if (score > max) {
                        max = score;
                        topUser = (String) user.get("name");
                    }
                }
                result.put("average", total / count);
                result.put("maxScore", max);
                result.put("topUser", topUser);
                result.put("count", count);
                return result;
            }
        };
        // 处理用户数据:按分数排序
        DataProcessor sorter = new DataProcessor() {
            @Override
            public Map<String, Object> process(List<Map<String, Object>> data) {
                // 简单的排序逻辑(这里仅统计)
                Map<String, Object> result = new HashMap<>();
                int passCount = 0;
                int failCount = 0;
                for (Map<String, Object> user : data) {
                    int score = (int) user.get("score");
                    if (score >= 70) {
                        passCount++;
                    } else {
                        failCount++;
                    }
                }
                result.put("passCount", passCount);
                result.put("failCount", failCount);
                result.put("passRate", (passCount * 100.0) / data.size());
                return result;
            }
        };
        // 执行分析
        Map<String, Object> statistics = scoreAnalyzer.process(users);
        System.out.println("=== 用户数据分析结果 ===");
        System.out.println("平均分: " + statistics.get("average"));
        System.out.println("最高分: " + statistics.get("maxScore"));
        System.out.println("最高分用户: " + statistics.get("topUser"));
        Map<String, Object> passStats = sorter.process(users);
        System.out.println("\n=== 通过率分析 ===");
        System.out.println("通过人数: " + passStats.get("passCount"));
        System.out.println("未通过人数: " + passStats.get("failCount"));
        System.out.printf("通过率: %.1f%%\n", passStats.get("passRate"));
    }
}

匿名内部类特点总结

优点:

  1. 简洁性:不需要单独创建类文件
  2. 局部性:只在需要的地方定义
  3. 可访问外部变量:可以访问外部类的成员变量和方法

注意事项:

  1. 访问外部变量:访问外部方法的局部变量时,该变量必须为final或effectively final
  2. 不能有静态成员:匿名内部类中不能定义静态成员
  3. 实例初始化:在内部类初始化后执行,可以通过实例初始化块进行额外配置

Lambda表达式替代:

在Java 8+中,如果匿名内部类主要实现函数式接口,可以简化为Lambda表达式:

// 匿名内部类方式
Runnable r1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello");
    }
};
// Lambda表达式方式
Runnable r2 = () -> System.out.println("Hello");

这些案例涵盖了匿名内部类的主要使用场景,从简单的接口实现到复杂的业务逻辑处理。

抱歉,评论功能暂时关闭!