Java Interface as argument to a method

14,153

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!

Share:
14,153
grpolylogic
Author by

grpolylogic

Updated on July 26, 2022

Comments

  • grpolylogic
    grpolylogic almost 2 years

    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.

    • pskink
      pskink over 7 years
      does that mean that an object of every class that implements this interface can be passed as argument? yes
    • Brunaldo
      Brunaldo over 7 years
      Yes, look at Polymorphism.