</>
Skip to content
Java lessons (33/47)

Java — Interfaces

Basic interface

interface Drawable {
    void draw();
}

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

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

Multiple interfaces

interface Printable {
    void print();
}

interface Loggable {
    void log();
}

class Document implements Printable, Loggable {
    @Override
    public void print() {
        System.out.println("Printing document");
    }

    @Override
    public void log() {
        System.out.println("Logging document");
    }
}

Interface with default methods

interface Logger {
    void log(String message);

    default void error(String message) {
        log("[ERROR] " + message);
    }

    static void info(String message) {
        System.out.println("[INFO] " + message);
    }
}

class ConsoleLogger implements Logger {
    @Override
    public void log(String message) {
        System.out.println("[LOG] " + message);
    }
}

Functional interface

@FunctionalInterface
interface MathOperation {
    int apply(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        MathOperation add = (a, b) -> a + b;
        MathOperation mul = (a, b) -> a * b;

        System.out.println(add.apply(3, 4)); // 7
        System.out.println(mul.apply(3, 4)); // 12
    }
}

Abstract class vs interface

FeatureAbstract ClassInterface
Multiple inheritanceNoYes
ConstructorsYesNo
State (fields)YesOnly constants
MethodsAbstract + concreteAbstract + default

Mini Practice

Write Java code that:

  1. Defines an interface with abstract and default methods
  2. Implements multiple interfaces in one class
  3. Creates a functional interface with a lambda

Up Next

In the next lesson, you'll learn about Enums — enumerations in Java.

Related Topics

Frequently Asked Questions about Interfaces

What is Interfaces in Java?

Interfaces is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Interfaces?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Interfaces.

Why is Interfaces important in Java?

Interfaces is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.