Java Interfaces Tutorial

An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body.

Why use Java Interface?

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

Syntax

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

Java Interface Example

interface Drawable {
    void draw();
}

class Rectangle implements Drawable {
    public void draw() {
        System.out.println("drawing rectangle");
    }
}

class Circle implements Drawable {
    public void draw() {
        System.out.println("drawing circle");
    }
}

class TestInterface1 {
    public static void main(String args[]) {
        Drawable d = new Circle();
        d.draw();  
    }
}

Java 8 Interface Improvements

Since Java 8, we can have default and static methods in an interface.

Default Method Example

interface Drawable {
    void draw();
    default void msg() {
        System.out.println("default method");
    }
}