Java - Interface Static Methods Declarations

Introduction

You can have static methods in interfaces.

A static method contains the static modifier.

They are implicitly public.

interface Walkable {
        // An abstract method
        void walk();

        // A static convenience method
        public static void letThemWalk(Walkable[] list) {
                for (int i = 0; i < list.length; i++) {
                        list[i].walk();
                }
        }
}

You can use the static methods of an interface using the dot notation.

<interface-name>.<static-method>

The following code calls the Walkable.letThemWalk() method:

Walkable[] w = new Walkable[4];
w[0] = new Person("A");
w[1] = new Duck("B");
w[2] = new Person("C");
w[3] = new Cat("Mary");
// Let everyone walk
Walkable.letThemWalk(w);

Demo

interface Walkable {
  void walk();  /*from   w  w w .  j  a va 2  s  .  c  om*/
  public static void letThemWalk(Walkable[] list) {
    for (Walkable w : list) {
      w.walk();
    }
  }
}

// The Person Class, Which Implements the Walkable Interface
class Person implements Walkable {
  private String name;

  public Person(String name) {
    this.name = name;
  }

  public void walk() {
    System.out.println(name + " (a person) is walking.");
  }
}

// The Duck Class, Which Implements the Walkable Interface

class Duck implements Walkable {
  private String name;

  public Duck(String name) {
    this.name = name;
  }

  public void walk() {
    System.out.println(name + " (a duck) is walking.");
  }
}
class Cat implements Walkable {
  private String name;

  public Cat(String name) {
    this.name = name;
  }

  public void walk() {
    System.out.println(name + " (a cat) is walking.");
  }
}

public class Main {
  public static void main(String[] args) {
    Walkable[] w = new Walkable[4];
    w[0] = new Person("A");
    w[1] = new Duck("B");
    w[2] = new Person("C");
    w[3] = new Cat("Mary");
    // Let everyone walk
    Walkable.letThemWalk(w);
  }
}

Result