Java 101Using an interface as a parameter

time to read 1 min | 151 words

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) {
    t.test(); 
  } // 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.


This is a post in the Java 101 series.
Other posts in this series:

  1. Apr 29, 2017 Translating Scanner tokens into primitive types
  2. Apr 28, 2017 Listing a file system's root directories
  3. Apr 27, 2017 The Console class
  4. Apr 20, 2017 Using an interface as a parameter
  5. Apr 19, 2017 Using bounded type parameters in generic methods
  6. Apr 18, 2017 Using the Deprecated annotation
  7. Apr 17, 2017 Diamond Operator in Java
  8. Apr 15, 2017 Altering format string output by changing a format specifier's argument_index
  9. Apr 13, 2017 Future of Interface in Java 9
  10. Apr 12, 2017 More about Interface in Java 8
  11. Apr 10, 2017 Manage Your JVM Environment with SDKMAN
  12. Apr 09, 2017 Updating interfaces by using default methods
  13. Apr 08, 2017 Converting Stacktrace to String

Related Post:

  1. Apr 29, 2017 Translating Scanner tokens into primitive types
  2. Apr 28, 2017 Listing a file system's root directories
  3. Apr 27, 2017 The Console class
  4. Apr 19, 2017 Using bounded type parameters in generic methods
  5. Apr 18, 2017 Using the Deprecated annotation
  6. Apr 17, 2017 Diamond Operator in Java
  7. Apr 15, 2017 Altering format string output by changing a format specifier's argument_index
  8. Apr 13, 2017 Future of Interface in Java 9
  9. Apr 12, 2017 More about Interface in Java 8
  10. Apr 11, 2017 Spring Boot in a Single File
  11. Apr 10, 2017 Manage Your JVM Environment with SDKMAN
  12. Apr 09, 2017 Updating interfaces by using default methods
  13. Apr 08, 2017 Converting Stacktrace to String
  14. Apr 07, 2017 Synchronized Statement in Java
  15. Jul 12, 2016 Fix Java Unsupported major.minor version 52.0 on Ubuntu