Java 101Updating interfaces by using default methods

time to read 1 min | 127 words

Take the following interface:

public interface Cooking {
  public void fry();
  public void boil();
  public void chop();
}

To add new functionality, simply adding a new method to Cooking called microwave() will cause problems. Any class that previously implemented Cooking will now have to be updated in order to function again.

To avoid this, give microwave() a default implementation:

public interface Cooking {
  public void fry();
  public void boil();
  public void chop();
  default void microwave() {
    //some code implementing microwave
  }
}

As microwave() already has a default implementation defined in the Cooking interface definition, classes that implement it now don’t need to implement microwave() in order to work.

This allows us to add functionality without breaking old code.

Note: This has been possible since Java 8.


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 26, 2017 Next, Function or Method ?
  5. Apr 20, 2017 Using an interface as a parameter
  6. Apr 19, 2017 Using bounded type parameters in generic methods
  7. Apr 18, 2017 Using the Deprecated annotation
  8. Apr 17, 2017 Diamond Operator in Java
  9. Apr 15, 2017 Altering format string output by changing a format specifier's argument_index
  10. Apr 13, 2017 Future of Interface in Java 9
  11. Apr 12, 2017 More about Interface in Java 8
  12. Apr 11, 2017 Spring Boot in a Single File
  13. Apr 10, 2017 Manage Your JVM Environment with SDKMAN
  14. Apr 08, 2017 Converting Stacktrace to String
  15. Apr 07, 2017 Synchronized Statement in Java
  16. Jul 12, 2016 Fix Java Unsupported major.minor version 52.0 on Ubuntu