interface

Java Interfaces

Java Interfaces

An interface in Java is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It is used to specify a set of methods that a class must implement.

Creating and Implementing an Interface

interface Animal {
    void sound();  // Abstract method
}

class Dog implements Animal {
    public void sound() {
        System.out.println("Woof");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound();
    }
}
    

The Dog class implements the Animal interface and provides the implementation for the sound() method.

Multiple Interface Implementation

interface Animal {
    void sound();
}

interface Playable {
    void play();
}

class Dog implements Animal, Playable {
    public void sound() {
        System.out.println("Woof");
    }

    public void play() {
        System.out.println("Playing fetch");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound();
        dog.play();
    }
}
    

Java allows a class to implement multiple interfaces. In this example, the Dog class implements both Animal and Playable interfaces.