0
0
Javaprogramming~5 mins

Interface declaration in Java

Choose your learning style9 modes available
Introduction

An interface in Java is like a contract that says what methods a class must have, without saying how they work.

When you want different classes to share the same set of actions but do them differently.
When you want to make sure a class follows certain rules or behaviors.
When you want to separate what something does from how it does it.
When you want to use multiple inheritance of type, since Java classes can only extend one class.
When you want to design flexible and reusable code.
Syntax
Java
public interface InterfaceName {
    // method signatures
    returnType methodName(parameters);
}

Interfaces only declare methods; they do not provide method bodies (except default or static methods in newer Java versions).

All methods in an interface are implicitly public and abstract.

Examples
This interface says any class that is an Animal must have eat and sleep methods.
Java
public interface Animal {
    void eat();
    void sleep();
}
Here, Vehicle interface requires a getSpeed method that returns an integer.
Java
interface Vehicle {
    int getSpeed();
}
This interface has a default method info with a body, which classes can use or override.
Java
public interface Drawable {
    void draw();
    default void info() {
        System.out.println("Drawable object");
    }
}
Sample Program

This program defines an interface Printer with a print method. ConsolePrinter class implements Printer and provides the print method. The main method creates a ConsolePrinter and calls print.

Java
public interface Printer {
    void print(String message);
}

public class ConsolePrinter implements Printer {
    public void print(String message) {
        System.out.println(message);
    }
}

public class Main {
    public static void main(String[] args) {
        Printer printer = new ConsolePrinter();
        printer.print("Hello, Interface!");
    }
}
OutputSuccess
Important Notes

Interfaces cannot have instance fields (variables), only constants (static final).

A class can implement multiple interfaces, helping with flexible design.

Since Java 8, interfaces can have default and static methods with bodies.

Summary

Interfaces define what methods a class must have, without how they work.

Use interfaces to ensure classes follow certain behaviors.

Interfaces help write flexible and reusable code by separating method declaration from implementation.