default

  • aka Defender Methods or Virtual extension methods
  • Used in interfaces
  • Applications:
    • for backward compatibility
    • introduce utility methods
    • bridge gap between interface and abstract class
  • Example for backward compatibility
    • If you want to add new method turnRight() in following Movable interface, then it will break all the implementation
    • Using default you can provide a default implementation and override implementation whenever required
interface Movable {
    void turnLeft();
    default void turnRight() {
        // default implementation
    }
}
 
class Batman implements Movable {
    public void turnLeft() {...}
}

Diamond problem

  • If a class implements two interfaces having same default methods, then the compiler forces a programmer to provide the implementation explicitly, otherwise it raises a compilation exception.
interface Movable {
    void stepAhead();
    void turnLeft();
    void turnRight();
 
    default void turnAround() {
        turnLeft();
        turnLeft();
    }
}
 
interface Jumpable {
    void jump();
    void turnLeftJump();
    void turnRightJump();
    default void turnAround() {
        turnLeftJump();
        turnLeftJump();
    }
}
 
class Batman implements Movable, Jumpable {
    // define an implementation for abstract methods
    public void stepAhead() {...}
    public void turnLeft() {...}
    public void turnRight() {...}
    public void jump() {...}
    public void turnLeftJump() {...}
    public void turnRightJump() {...}
 
    // If you don't implement it then compilation error
    // define an implementation for conflicting default method
    public void turnAround() {
        // define turnaround for Spiderman
        Movable.super.turnAround(); // choose one of the default implementation
    }
}