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");
    }
}

Frequently Asked Questions

What will I learn here?

This page covers the core concepts and techniques you need to understand the topic and progress confidently to the next lesson.

How should I use this page?

Start with the overview, then follow the section links to deepen your understanding. Use the table of contents on the right to jump to specific sections.

What should I read next?

Use the navigation below to continue to the next lesson or explore related topics.