gpt4 book ai didi

Java 接口(interface)作为方法的参数

转载 作者:行者123 更新时间:2023-12-01 21:15:40 24 4
gpt4 key购买 nike

在某些 Java 方法中,我发现需要 Interface 参数。由于接口(interface)无法实例化,这是否意味着实现该接口(interface)的每个类的对象都可以作为参数传递?

例如Android中ListView类的setOnClickListener方法中,

setOnItemClickListener(AdapterView.OnItemClickListener listener)

需要 OnItemClickListener 接口(interface)(嵌套在 AdapterView 抽象类中)作为参数。

这里需要传递什么样的对象?

提前谢谢您。

最佳答案

是的 - 如果需要接口(interface)类型作为参数,则可以传递其类实现此接口(interface)的任何对象。

示例:

// the method
void myMethod(MyInterface object) { ... }

// the interface
interface MyInterface {

void interfaceMethod();

}

// class implementing the interface
class MyImplementation implements MyInterface {

void interfaceMethod() {
// ...
}

}

您现在可以执行此操作

MyInterface object = new MyImplementation();
myMethod(object);

希望这有帮助!

关于Java 接口(interface)作为方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com