Java - Interface Default Methods Declarations

What is interface default method?

A default method from interface provides a default implementation, but does not override the default method.

default method are added so the existing interfaces may evolve.

Syntax

A default method in an interface is declared with the modifier default.

A default method cannot be declared abstract or static.

It must provide an implementation.

Demo

interface Movable {
  void setX(double x);

  void setY(double y);

  double getX();/*from w  w w .j a  v  a 2 s .  c  o m*/

  double getY();

  // A default method
  default void move(double deltaX, double deltaY) {
    double newX = getX() + deltaX;
    double newY = getY() + deltaY;
    setX(newX);
    setY(newY);
  }
}

class Pen implements Movable {
  private double x, y;

  @Override
  public void setX(double x) {
    this.x = x;
  }

  @Override
  public void setY(double y) {
    this.y = y;
  }

  @Override
  public double getX() {
    return x;
  }

  @Override
  public double getY() {
    return y;
  }

  @Override
  public String toString() {
    return "Pen [x=" + x + ", y=" + y + "]";
  }

}

public class Main {
  public static void main(String[] args) {
    // Create a Pen and assign its reference to a Movable variable
    Movable p1 = new Pen();
    System.out.println(p1);

    // Move the Pen using absolute cocordinates
    p1.setX(10.0);
    p1.setY(5.0);
    System.out.println(p1);

    // Move the Pen using relative cocordinates
    p1.move(5.0, 2.0);
    System.out.println(p1);
  }
}

Result