MST

星途 面试题库

面试题:Java中如何通过接口实现简单的回调机制

请简述在Java中利用接口实现回调机制的基本步骤,并给出一个简单的代码示例,要求包含接口定义、实现类以及调用回调的部分。
19.4万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 基本步骤
    • 定义一个接口,接口中声明回调方法。
    • 实现该接口,在实现类中编写回调方法的具体逻辑。
    • 在调用方中,通过将实现类的实例作为参数传递给某个方法,在合适的时机调用接口中的回调方法。
  2. 代码示例
// 1. 定义接口
interface CallbackInterface {
    void callbackMethod(String message);
}

// 2. 实现类
class CallbackImplementation implements CallbackInterface {
    @Override
    public void callbackMethod(String message) {
        System.out.println("回调方法被调用,收到消息: " + message);
    }
}

// 3. 调用回调的部分
class Caller {
    public void executeCallback(CallbackInterface callback, String message) {
        callback.callbackMethod(message);
    }
}

可以通过以下方式测试:

public class Main {
    public static void main(String[] args) {
        Caller caller = new Caller();
        CallbackImplementation implementation = new CallbackImplementation();
        caller.executeCallback(implementation, "Hello, Callback!");
    }
}