DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

Interface in Java

An interface in Java is a blueprint of a class.

It contains:

  • method declarations
  • constants

But usually it does not contain full method implementation.

Interface tells:

  • What to do
  • not
  • How to do

Syntax

interface Animal {

    void sound();

}
Enter fullscreen mode Exit fullscreen mode

Here:

  • Animal is interface
  • sound() has no body

Implementing Interface

class Dog implements Animal {

    public void sound() {
        System.out.println("Bark");
    }

}
Enter fullscreen mode Exit fullscreen mode

implements keyword is used.


Why use Interface?

1. Achieve Abstraction

Hide internal details.

void sound();
Enter fullscreen mode Exit fullscreen mode

Only rule is given.

2. Multiple Inheritance

Java does not support:

class A extends B, C
Enter fullscreen mode Exit fullscreen mode

But interface allows multiple inheritance.

interface A {}
interface B {}

class Test implements A, B {}
Enter fullscreen mode Exit fullscreen mode

Variables in interface are:

Automatically:

public static final
Enter fullscreen mode Exit fullscreen mode

Example:

interface Test {

    int x = 10;

}
Enter fullscreen mode Exit fullscreen mode

Same as:

public static final int x = 10;
Enter fullscreen mode Exit fullscreen mode

Methods are automatically:

public abstract
Enter fullscreen mode Exit fullscreen mode

Top comments (0)