English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input Output (I/)

Java Reader/Writer

Java Other Topics

Java Interfaces (Interface)

In this tutorial, we will learn about Java interfaces. We will learn how to implement interfaces and when to use them through examples.

In Java, an interface defines a set of specifications that other classes must implement. For example,

interface Polygon {
   public void getArea();
}

Here, Polygon is an interface. We use the interface keyword to declare an interface.

The getArea() method is defined as a specification in the Polygon interface. All classes that use this interface must implement the getArea() method.

Interfaces can contain abstract methods and constants. For example,

interface Polygon {
   public static final String color = "blue";
   
   public void getArea();
}

In the above example, we created an interface called Polygon. It includes a constant variable color and an abstract method getArea().

It is important to note that all methods within the interface are implicitly public, and all fields are implicitly public static final. Therefore, there is no need to specify the access modifier within the interface. For example, we can write the above code as

interface Polygon {
   String color = "blue";
   
    void getArea();
}

Interface and implements keyword

Like abstract classes, we cannot create objects of interfaces. However, we can implement interfaces in other classes. In Java, we use the implements keyword to implement an interface. For example,

interface Polygon {
    void getArea(int length, int breadth);
}
class Rectangle implements Polygon {
    public void getArea(int length, int breadth) {
        System.out.println("The area of the rectangle is ", + (length * breadth));
    }
}
class Main {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();
        r1.getArea(5, 6);
    }
}

Output result

The area of a rectangle is 30

In the above program, we created an interface Polygon. The Polygon interface has an abstract method getArea().

 This means that any class implementing Polygon must provide an implementation for the getArea() method.

Note that the Rectangle class (implementing the Polygon interface) has a method getArea() with an implementation.

Why use interfaces?

Now that we know what an interface is, let's understand why we use interfaces in Java.

  • Interfaces provide specifications that classes (implementing them) must follow.

  • In the above example, we have used getArea() as a specification in the interface Polygon. This is like setting a rule that we should be able to obtain the area of each polygon. Therefore, any class that implements the Polygon interface must provide an implementation of the getArea() method.

  • Similar to abstract classes, interfaces can help us achieve Java abstraction. Here, we know that getArea() calculates the area of a polygon, but the way to calculate the area is different for different polygons. Therefore, the implementations of getArea() are independent of each other.

  • Interfaces are also used to achieve multiple inheritance in Java. If a subclass inherits from two or more classes, it is considered multiple inheritance.

    In Java, it is not possible to achieve multiple inheritance through class inheritance. However, a class can implement multiple interfaces. This allows us to obtain the functionality of multiple inheritance in Java. For example,

    interface Line {
       ...
    }
    interface Polygon {
       ...
    }
    class Rectangle implements Line, Polygon{
       ...
    }

    Here, Rectangle must provide implementations for all methods of Line and Polygon.

Private methods and static methods in interfaces

Java 8Currently, interfaces can include static methods.

Similar to classes, we can use references to access the static methods of interfaces. For example,

Polygon.staticMethod();

Additionally, interfaces in Java 9Supports private methods in the release version. Now, you can useprivate methodandPrivate static method.

Since interfaces cannot be instantiated, private methods are used as auxiliary methods to support other methods within the interface.

default methods in interfaces

Java 8In which, default methods with implementations were introduced within the interface (default methods), while before that, all methods were abstract methods in Java.

To declare a default method within an interface, we use the default keyword. For example,

public default void getSides() {
   //The body of getSides()
}

Why use default methods?

Let's take a scenario to understand why default methods were introduced in Java.

Suppose we need to add a new method to the interface.

We can easily add this method to the interface without execution. However, this is not the end of the story. All the classes that implement this interface must provide the implementation of this method.

If a large number of classes are implementing this interface, we need to track all these classes and make changes to them. This is not only cumbersome but also prone to errors.

To solve this problem, Java introduced default methods. Default methods inherit like ordinary methods.

Let's take an instance to better understand the default method.

Example2: default method

interface Polygon {
   void getArea();
   default void getSides() {
      System.out.println("I can get the sides of the polygon.");
   }
}
class Rectangle implements Polygon {
   public void getArea() {
      int length = 6;
      int breadth = 5;
      int area = length * breadth;
      System.out.println("The area of the rectangle is ",+area);
   }
   public void getSides() {
      System.out.println("I have four sides.");
   }
}
class Square implements Polygon {
   public void getArea() {
      int length = 5;
      int area = length * length;
      System.out.println("The area of the square is ",+area);
   }
}
class Main {
   public static void main(String[] args) {
      Rectangle r1 = new Rectangle();
      r1.getArea();
      r1.getSides();
      Square s1 = new Square();
      s1.getArea();
   }
}

Output result

The area of a rectangle is 30
I have four sides.
The area of a square is 25

In the above example, we created a Polygon interface. Polygon has a default method getSides() and an abstract method getArea().

Then, the Rectangle class implements Polygon, Rectangle provides the implementation of the abstract method getArea(), and overrides the default method getSides().

We created another Square class, which also implements Polygon. Here, Square only provides the implementation of the abstract method getArea().

Actual application example of the interface

Let's look at a more practical Java interface example.

//Use the sqrt function
import java.lang.Math;
interface Polygon {
   void getArea();
  
     //Calculate the perimeter of the polygon
   default void getPerimeter(int... sides) {
      int perimeter = 0;
      for (int side: sides) {
         perimeter += side;
      }
   System.out.println("Perimeter: " + perimeter);
   }
}
class Triangle implements Polygon {
   private int a, b, c;
   private double s, area;
    //Initialize the sides of the triangle
   Triangle(int a, int b, int c) {
      this.a = a;
      this.b = b;
      this.c = c;
      s = 0;
   }
    //Calculate the area of the triangle
   public void getArea() {
      s = (double) (a + b + c)/2;
      area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
      System.out.println("Area: " + area);
   }
}
class Main {
   public static void main(String[] args) {
      Triangle t1 = new Triangle(2, 3, 4);
      //Call the method of Triangle class
      t1.getArea();
      //Call the method of Polygon class
      t1.getPerimeter(2, 3, 4);
   }
}

Output result

Area: 2.9047375096555625
Perimeter: 9

In the above program, we created an interface Polygon. It includes the default method getParameter() and the abstract method getArea().

We can calculate the perimeter of all polygons in the same way, therefore we have implemented the main body of getPerimeter() in the Polygon class. Now, all polygons that implement Polygon can use getPerimeter() to calculate the perimeter.

However, the method of calculating the area is different for different polygons, because the rule for calculating the area is different for different polygons.

Therefore, getArea() is included without implementation in Polygon. And, any class that implements the Polygon interface must provide an implementation for getArea().

Interface and 'extends' keyword

Like classes, interfaces can inherit other interfaces, and the 'extends' keyword is used for inheritance. For example,

interface Line {
   //Members of Line interface
}
interface Polygon extends Line {
   //Members of Polygon interface and Line interface
}

In the above example, the interface Polygon extends the Line interface. Now, if a class implements Polygon, it should provide implementations for all the abstract classes of Line and Polygon.

Note that an interface can inherit multiple interfaces, similar to a class that implements multiple interfaces. For example,

interface A {
   ...
}
interface B {
   ... 
}
Interface C extends A, B {
   ...
}