Interface in Java | OOP Concept in Java

An interface in Java is a reference type, similar to a class, that contains only constants, method signatures, default methods, static methods, and nested types. Interfaces are used to achieve full abstraction and multiple inheritance in Java, allowing classes to implement several interfaces.

Key Points on Interface:

Syntax of Interface:

Syntax Example

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

Example of Interface in Java:

This example demonstrates an interface Animal with an abstract method sound(). The Dog class implements the Animal interface, providing its own implementation of the sound() method.

Code Example

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

class Dog implements Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks.");
    }
    
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound(); // Calls implemented method
    }
}

Output

Dog barks.

Detailed Explanation:

Using interfaces effectively helps achieve full abstraction and makes code more flexible, as multiple classes can implement the same interface, adhering to a specific contract.