Java接口作为方法的参数 [英] Java Interface as argument to a method

查看:967
本文介绍了Java接口作为方法的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In some Java methods I see that an Interface argument is required. Since an Interface cannot be instantiated, does that mean that an object of every class that implements this interface can be passed as argument?

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

For example in the setOnClickListener method of the ListView class in Android,

setOnItemClickListener(AdapterView.OnItemClickListener listener)

需要OnItemClickListener接口(位于AdapterView抽象类中)作为参数.

the OnItemClickListener interface (nested in the AdapterView abstract class) is needed as an argument.

需要在此处传递哪种对象?

What kind of object is required to be passed here?

谢谢.

推荐答案

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

Yes - if an interface type is required as an argument, you can pass any object whose class implements this 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接口作为方法的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆