1. 匿名内部类的使用案例

// 定义接口
interface MyInterface {
    void doSomething();
}

// 定义类,并设计一个方法接受接口实例
class MyClass {
    void performAction(MyInterface myInterface) {
        myInterface.doSomething();
    }
}

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        
        // 使用匿名内部类传递给方法
        myClass.performAction(new MyInterface() {
            @Override
            public void doSomething() {
                System.out.println('调用了匿名内部类的doSomething方法');
            }
        });
    }
}

运行结果:

调用了匿名内部类的doSomething方法

2. 覆盖 Object 类的 toString 和 equals 方法的示例

class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 覆盖 toString 方法
    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + "}";
    }

    // 覆盖 equals 方法
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Student student = (Student) obj;
        return age == student.age && name.equals(student.name);
    }
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student("Alice", 20);
        Student student2 = new Student("Bob", 21);
        Student student3 = new Student("Alice", 20);

        // 测试 toString 方法
        System.out.println(student1.toString());
        System.out.println(student2.toString());
        System.out.println(student3.toString());

        // 测试 equals 方法
        System.out.println(student1.equals(student2));
        System.out.println(student1.equals(student3));
    }
}

运行结果:

Student{name='Alice', age=20}
Student{name='Bob', age=21}
Student{name='Alice', age=20}
false
true

您可以在 Java 编译器中运行以上代码,或者使用集成开发环境(IDE)如 Eclipse、IntelliJ IDEA 等来运行代码,并查看控制台输出结果。


原文地址: https://www.cveoy.top/t/topic/RKp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录