Java - Interface Multiple Implementing

Introduction

A class can implement multiple interfaces.

All interfaces being implemented are listed after the keyword implements in the class declaration.

Demo

interface Adder {
  int add(int n1, int n2);
}

interface Subtractor {
  int subtract(int n1, int n2);
}

class ArithOps implements Adder, Subtractor {
  // Override the add() method of the Adder interface
  public int add(int n1, int n2) {
    return n1 + n2;
  }// w  w w . jav a2 s  . c o m

  // Override the subtract() method of the Subtractor interface
  public int subtract(int n1, int n2) {
    return n1 - n2;
  }
}

public class Main {
  public static void main(String[] args) {
    ArithOps a = new ArithOps();
    Adder b = new ArithOps();
    Subtractor c = new ArithOps();
    b = a;
    c = a;

  }
}

A Turtle Class, Which Implements the Walkable and Swimmable Interfaces

Demo

interface Swimmable {
  void swim();/*  w  ww.  j  a  v  a  2s. c  om*/
}

interface Walkable {
  void walk();
}

class Turtle implements Walkable, Swimmable {
  private String name;

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

  // Adding a bite() method to the Turtle class
  public void bite() {
    System.out.println(name + " (a turtle) is biting.");
  }

  // Implementation for the walk() method of the Walkable interface
  public void walk() {
    System.out.println(name + " (a turtle) is walking.");
  }

  // Implementation for the swim() method of the Swimmable interface
  public void swim() {
    System.out.println(name + " (a turtle) is swimming.");
  }
}

public class Main {
  public static void main(String[] args) {
    Turtle turti = new Turtle("Turti");
    // Using Turtle type as Turtle, Walkable and Swimmable
    letItBite(turti);
    letItWalk(turti);
    letItSwim(turti);
    // a Turtle type variable can access all three methods, bite(), walk(), and
    // swim() like so:

    Turtle t = new Turtle("Turti");
    t.bite();
    t.walk();
    t.swim();

    // When you use a Turtle object as the Walkable type, you can access only
    // the walk() method.

    // When you use a Turtle object as the Swimmable type, you can access only
    // the swim() method.
    t = new Turtle("Trach");
    Walkable w = t;
    w.walk(); // OK. Using w, you can access only the walk() method of Turtle
              // object

    Swimmable s = t;
    s.swim(); // OK. Using s you can access only the swim() method
  }

  public static void letItBite(Turtle t) {
    t.bite();
  }

  public static void letItWalk(Walkable w) {
    w.walk();
  }

  public static void letItSwim(Swimmable s) {
    s.swim();
  }

}

Result