java接口 参数,Java接口作为方法的参数

在Java中,当方法需要一个接口类型的参数时,你可以传入任何实现了该接口的类的对象。例如,Android中ListView的setOnItemClickListener方法需要一个AdapterView.OnItemClickListener接口作为参数。这意味着你可以创建一个实现该接口的类,并实例化这个类的对象来作为参数传递。这允许了代码的灵活性和多态性。
摘要由CSDN通过智能技术生成

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?

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

setOnItemClickListener(AdapterView.OnItemClickListener listener)

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

What kind of object is required to be passed here?

Thank you in advance.

解决方案

Yes - if an interface type is required as an argument, you can pass any object whose class implements this interface.

Example:

// the method

void myMethod(MyInterface object) { ... }

// the interface

interface MyInterface {

void interfaceMethod();

}

// class implementing the interface

class MyImplementation implements MyInterface {

void interfaceMethod() {

// ...

}

}

You can now do this

MyInterface object = new MyImplementation();

myMethod(object);

Hope this helps!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值