What is Interface in Java ? | Explain Interface in java?

 




In Java, an interface is a collection of abstract methods (methods without a body) that must be implemented by any class that implements the interface. 


Interfaces can also contain constant variables, default methods, and static methods.


An interface is defined using the interface keyword, and the methods within an interface are automatically public and abstract, so you don't need to include those modifiers. 


For example:



interface Shape {
 
  double getArea();
 
  double getPerimeter();
 
}


This is an interface called "Shape" that defines two abstract methods "getArea()" and "getPerimeter()".




To implement an interface, a class uses the implements keyword. A class can implement multiple interfaces. 



For example:



class Rectangle implements Shape {
 
  double width;
 
  double height;
 
  Rectangle(double w, double h) {
 
    width = w;
 
    height = h;
 
  }
 
  @Override
 
  public double getArea() {
 
    return width * height;
 
  }
 
  @Override
 
  public double getPerimeter() {
 
    return 2 * (width + height);
 
  }
 
}


In this example, the "Rectangle" class implements the "Shape" interface and provides an implementation for both methods "getArea()" and "getPerimeter()".




Java 8 introduces the concept of default methods and static methods in interfaces, which allows the interface to have methods with implementation and can be called directly on the interface.


interface Shape {
 
    public void draw();
 
    public default void printArea(){
 
        System.out.println("Calculating area...");
 
    }
 
    public static double getPi(){
 
        return 3.14;
 
    }
 
}



In this example, the interface "Shape" has a method "draw()" which is an abstract method, a default method "printArea()" which has the implementation and a static method "getPi()" which can be called directly on the interface.



Interfaces are useful in situations where you want to define a contract or set of rules that must be followed by any class that implements the interface. 

It allows for a clear separation of concerns and helps to promote code reuse and flexibility by allowing different classes to implement the same interface.

Post a Comment

Post a Comment (0)

Previous Post Next Post