Interfaces in Java

Interface in Java is a blue print of  a class.It has static constants and abstraction methods. Interface  can be implemented using the keyword “implements”.The interface keyword is used  to declare interface.

Example:  public  interface  Drawable{

void   draw();

}

Why we use Java Interface?

 

There are many reasons to use interface in java. They are :

  • it is used to achieve abstraction.
  • And also it can able to support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

Syntax:

interface <interface_name>{

//declare constant fields

//declare methods that abstract

//by default

 

Key points on Interface in Java :

  1. Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
  2. Interface has only static and final variables.
  3. Interface can’t provide the implementation of abstract class.
  4. Members of a Java interface are public by default.

Types of Interfaces

  1. Functional Interface
  2. Marker Interface

Functional interface : A functional interface in Java is an Interface with a single abstract method(SAM) that can also have multiple default and static methods.The ‘@FunctionalInterface’ annotation is used to designate an interface as a functional interface.

 

Marker Interface : Marker Interface in Java is an empty interface with no methods or fields. It is used to provide metadata to classes and enable various functionalities.

//Define the interface
interface Bird {
    void makeSound();
    int getNumberOfLegs();
}

//Implement the interface in a class 
class Parrot implements Bird {
    public void makeSound() {
       System.out.println("kech kechhhh!");
    }
    
    public int getNumberOfLegs() {
         return 2;
    }
}

//Use the implementations
public class Main {
    public static void main(String[] args) {
        Bird Parrot = new Parrot();
        Parrot.makeSound();
        System.out.println(Parrot.getNumberOfLegs());
    }
}

OUTPUT

 

kech kechhhh!
2

=== Code Execution Successful ===

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top