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!