Why the default method?
When you implement an interface, that interface may change. It may add more methods by which you will be forced to implement. Default methods solved this issue in where you don’t need to implement default methods. There are just there for you to use. There is no need for you to modify anything in your class.
The most typical use of default methods in interfaces is to incrementally provide additional functionality to a given type without breaking down the implementing classes. In addition, they can be used to provide additional functionality around an existing abstract method:
public interface Screen { public boolean turnOn(); public boolean turnOff(); // default method default void defaultMethod() { System.out.println("Doing Screen default things..."); } }
public class DefaultStaticMethodDemo implements Screen{ public static void main(String[] args) { DefaultStaticMethodDemo demo = new DefaultStaticMethodDemo(); demo.defaultMethod(); } @Override public boolean turnOn() { // TODO Auto-generated method stub return true; } @Override public boolean turnOff() { // TODO Auto-generated method stub return false; } }
Implementing multiple interfaces with the same default method names.
public interface Vehicle { // default method default void defaultMethod() { System.out.println("Doing Vehicle default things..."); } }
It won’t compile. You have to provide your own implementation.
public class DefaultStaticMethodDemo implements Screen, Vehicle{ public static void main(String[] args) { DefaultStaticMethodDemo demo = new DefaultStaticMethodDemo(); demo.defaultMethod(); } @Override public boolean turnOn() { // TODO Auto-generated method stub return true; } @Override public boolean turnOff() { // TODO Auto-generated method stub return false; } }
public class DefaultStaticMethodDemo implements Screen, Vehicle{ public static void main(String[] args) { DefaultStaticMethodDemo demo = new DefaultStaticMethodDemo(); demo.defaultMethod(); } @Override public boolean turnOn() { // TODO Auto-generated method stub return true; } @Override public boolean turnOff() { // TODO Auto-generated method stub return false; } @Override public void defaultMethod() { // TODO Auto-generated method stub Vehicle.super.defaultMethod(); } }
Having static methods in your interface helps group all related methods into one place. You have all your interface functions as well as utility functions.
public interface Vehicle { public boolean turnOn(); // default method default void defaultMethod() { System.out.println("Doing Vehicle default things..."); } static double getApproximateDistance(double milePerGallon, double gallons) { return milePerGallon*gallons; } }