Interfaces in Java

An INTERFACE IN JAVA programming is defined as an abstract type used to specify the class behavior, just like protocols do. A Java interface contains static constants and abstract methods. A class can implement multiple interfaces. In Java, interfaces are declared using the interface keyword. All methods in the interface are implicitly public and abstract.



// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Dog "implements" the Animal interface
class Dog implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The Dog says: woof-woof");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    Dog myDog = new Dog();  // Create a Dog object
    myDog.animalSound();
    myDog.sleep();
  }
}

implements Keyword in Interface

Like abstract classes, we cannot create objects of interfaces. However, we can implement interfaces in other classes. In Java, we use the implements keyword to implement interfaces.

Syntax :

interface <interface_name> {
    
    // declare constant fields
    // declare methods that abstract 
    // by default.
}

Why do we use interface ?

  • It is used to achieve total abstraction.
  • Since java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance .
  • It is also used to achieve loose coupling.
  • Interfaces are used to implement abstraction. So the question arises why use interfaces when we have abstract classes?