Using an interface as a parameter
Thu Apr 20, 2017 · 151 words
Java Interface Parameter

You can define methods that take an interface as a parameter. Your interface defines a contract and your methods will accept as parameter any objects whose class implements that interface. This is in fact one of the most common and useful ways to use an interface.

interface Test {
  public void test(); //define the interface

class Tester {
  public void runTest(Test t) {
  } // method with interface as param

MyTest class will implement this interface:

class MyTest implements Test {
  public void test() { // running code }

Now the runTest method will take as a parameter any object that implements the Test Interface:

Tester tester = new Tester(); Test test1 = new MyTest(); tester.runTest(test1);

The collection framework from the standard Java API frequently uses this procedure. For example, Collections.sort() can sort any class that implements the List interface and whose contents implement the Comparable interface.

back · he thought · he could · so he did · main