Java - Interface Java Interface

What Is an Interface?

An interface in Java defines a reference type to specify an abstract concept.

It is implemented by classes that provide an implementation of the concept.

Interfaces define a relationship between unrelated classes through the abstract concept.

An interface is declared using the keyword interface, which can have abstract method declarations.

Syntax

The general syntax for declaring an interface is

<modifiers> interface <interface-name> {
        Constant-Declaration
        Method-Declaration
        Nested-Type-Declaration
}

Demo

interface Walkable {
  void walk();/*from w  w  w.ja v a 2  s .co m*/
}

// 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 Walkables {
  public static void letThemWalk(Walkable[] list) {
    for (Walkable w : list) {
      w.walk();
    }
  }
}

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
    Walkables.letThemWalk(w);
  }
}

Result

Related Topics