Java - Interface Interface Implementing

Syntax

The general syntax for a class declaration that implements an interface looks as follows:

<modifiers> class <class-Name> implements <comma-separated-list-of-interfaces> {
        // Class body goes here
}

Suppose there is a Fish class.

interface Swimmable{
   void swim();
}
class Fish implements Swimmable {
        //  Override and implement the swim() method
        public void swim() {
                // Code for swim method goes here
        }
}

The class that implements an interface must override to implement all abstract methods declared in the interface.

Otherwise, the class must be declared abstract.

default methods of an interface are also inherited by the implementing classes.

The implementing classes may choose, but not required, to override the default methods.

The static methods in an interface are not inherited by the implementing classes.

Code for the Fish Class That Implements the Swimmable Interface

class Fish implements Swimmable {
  private String name;

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

  public void swim() {
    System.out.println(name + " (a fish) is swimming.");
  }
}

class Turtle implements Swimmable {
  public void swim() {
    System.out.println("Turtle can swim too!");
  }
}

interface Swimmable {
  void swim();
}

public class Main {
  public static void main(String[] args) {
    // Create an object of the Fish class
    Fish a = new Fish("A");
    Fish b = new Fish("B");
    Swimmable d = new Fish("C");

    a = b;
    // A Swimmable is not always a Fish
    a = d; // A compile-time error
    // A Fish is always Swimmable. However, not every Swimmable is a Fish.
    d = new Turtle(); // OK. A Turtle is always Swimmable
  }
}

Related Topics