Java 接口作为方法的参数

grp*_*gic 2 java methods android arguments interface

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

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

setOnItemClickListener(AdapterView.OnItemClickListener listener)
Run Code Online (Sandbox Code Playgroud)

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

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

先感谢您。

Mic*_*ihs 5

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

\n\n

例子:

\n\n
// the method\nvoid myMethod(MyInterface object) { ... }\n\n// the interface\ninterface MyInterface {\n\n    void interfaceMethod();\n\n}\n\n// class implementing the interface\nclass MyImplementation implements MyInterface\xc2\xa0{\n\n    void interfaceMethod() {\n        // ...\n    }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

你现在可以这样做

\n\n
MyInterface object = new MyImplementation();\nmyMethod(object);\n
Run Code Online (Sandbox Code Playgroud)\n\n

希望这可以帮助!

\n