Interface in Java

Interface In Java

In java, the interface is a pure abstract class used to group related methods with no bodies.

  • All the fields in interfaces are public, static, and final by default.
  • Interfaces support the functionality of multiple inheritances.
  • All methods are public and abstract by default.
  • A class that implements an interface must implement all the methods declared in the interface.

Why use Java interface?

There are mainly three reasons to use the interface. They are given below.

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritances.
  • It can be used to achieve loose coupling.

Syntax

interface InterfaceName{  
    // declare constant fields  
    // declare methods that abstract   
    // by default.  
}  

Example 1

Here we are declaring Vehicle as interface. It contains one method, i.e., run. Any class that wants to implement Vehicle must include the run method.

// declaring interface
interface Vehicle{
    // we must create run method to implement vehicle.
    void run();

}
// we use implements keyword for interface.
class Car implements Vehicle{
    public void run(){
        System.out.println("Car runs with 4 wheels.");
    }
}

class Bike implements  Vehicle{
    public void run(){
        System.out.println("Bike runs with 2 wheels.");
    }
}

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        Bike b = new Bike();
        c.run(); // print Car runs with 4 wheels.
        b.run(); // print Bike runs with 2 wheels.

    }
}
 
Show Output

Example 2

Here we are declaring Animal as the interface. It contains one method, i.e., sound. If any class wants to implement Animal, it must include the sound method.

// Interface Demo
interface Animal{
    void sound();
}

class Cow implements Animal{
    public  void sound(){
        System.out.println("Baa... Baaa...");
    }
}

class Dog implements Animal{
    public  void sound(){
        System.out.println("Bhoow....Bhoww....");
    }
}
public class Main {
    public static void main(String[] args) {
        Cow c = new Cow();
        Dog d = new Dog();
        c.sound();
        d.sound();

    }
}
Show Output