Realtime Use of Interface in Java Application

In the previous tutorial, we have known the basic of the interface in Java as well as its several advantages in utilizing the features of interfaces in general programming.

In general, when we write a simple program, nobody may think about the actual need to use an interface.

But when we are developing a larger application, it is a good idea to use an interface. We can use it in most areas of application development.

The major advantage of using an interface in Java is that it allows multiple inheritance.

Let’s understand the use of interface in Java with real-time examples. We will understand how Java interface concept is useful in real-time application and software development.

Use of Interface in Java Application with Example


Realtime Example 1:

Suppose you have some rupees in your hands. You can buy from this money something from that shop where billing is done in rupees.

Suppose you go to such a shop for buying where only dollars are accepted, you cannot use your rupees there. This money is like a class. A class can fulfill only a particular requirement. It is not useful to handle different situations.

Now suppose you have a credit card. In a shop, you can easily pay in rupees by using your credit card. If you go to another shop where dollars are accepted, you can also pay in dollars.

The same credit card can be used to pay in pounds as well. But how is this credit card paying in different currencies? Let’s understand it.

Basically, a credit card is like an interface that performs several tasks. It is a thin plastic card that contains identification information such as your name, bank name, and perhaps some numbers.

It does not hold any money physically. But here question is that how are shop keepers able to draw money from credit card?

Behind credit card, have our bank account details from where the money is transferred to shop keepers after authentication.

This bank account can be considered as an implementation class that actually performs different tasks. See the below figure to understand the concept.

Use of Interface in Java with realtime example

Real-time Example 2:

Suppose Amazon wants to integrate HDFC bank code into their shopping cart for their customer’s convenience. Amazon wants when their customers purchase any product from Amazon, then they do payment through HDFC bank.


But to do payment Amazon does not have its own HDFC bank. So, they will have to take the help of the HDFC bank. Let’s say HDFC developed codes as below.

class Transaction 
{ 
  void withdrawAmt(int amtToWithdraw) 
  { 
     // logic of withdraw. 
     // HDFC DB connection and updating in their DB. 
  } 
}

Now, Amazon needs this class to integrate the payment option. So they will request HDFC bank to get this. But the problem with HDFC is that if they give the total code to Amazon, then they are exposing everything of their database to them and logic will also get exposed which is a security violation.

Now what exactly Amazon needs is method name and class name. But to compile their class, they must get that class like below.

Transaction t = new Transaction(); 
  t.withdrawAmt(500);

If the first line has to compile at Amazon end, they must have this class which HDFC cannot give. The solution is here for HDFC that they develop an interface of Transaction class as given below.

Interface TransactionI 
{ 
  void withdrawAmt(int amtToWithdraw); 
 } 
class TransactionImpl implements TransactionI 
{ 
  void withdrawAmt(int amtToWithdraw) 
  { 
    // logic of withdraw. 
    // HDFC DB connection and updating in their DB. 
  } 
}

Amazon now will get an interface not class, they will use it as given below.

TransactionI ti = new TransactionImpl(); 
 // right hand side may be achieve by 
 // webservice or EJB 
   
  ti.withdrawAmt(500);

In this case, both parties achieve their goals. Amazon only needs the method name and parameter they got it. ICICI only wants to give them name, not logic so they provided. Also, it does not matter to ICICI what customers have purchased from Amazon. They just have to work for the amount of deduction.


Hope that you will have understood from the above realtime example that how to interface is very useful in realtime applications. Let us look at a glance at some more uses of interface in Java.

What is Use of Interface in Java?


There are mainly five reasons for using the interface in Java. They are as follows:

1. In industry, architect-level people create interfaces, and then it is given to developers for writing classes by implementing interfaces provided.

2. Using interfaces is the best way to expose our project’s API to some other project. For example, HDFC bank can expose methods or interfaces to various shopping carts.

3. Programmers use interface to customize features of software differently for different objects.

4. It is used to achieve fully abstraction.

Program code:

// Interface defining the abstract behavior
interface Drawable {
    void draw(); // Abstract method declaration
}

// Concrete classes implementing the Drawable interface
class Circle implements Drawable {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("Drawing a circle with radius " + radius);
     // Actual drawing logic can be implemented here
  }
}

class Rectangle implements Drawable {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public void draw() {
        System.out.println("Drawing a rectangle with length " + length + " and width " + width);
        // Actual drawing logic can be implemented here
    }
}

public class Main {
public static void main(String[] args) 
{
 // Create objects of Circle and Rectangle
    Circle circle = new Circle(5.0);
    Rectangle rectangle = new Rectangle(4.0, 6.0);

 // Call the draw method on both objects
    circle.draw();
    rectangle.draw();
  }
}
Output:
       Drawing a circle with radius 5.0
       Drawing a rectangle with length 4.0 and width 6.0

In this example, we have defined an interface named Drawable with an abstract method draw(). Two classes, Circle and Rectangle, implement the Drawable interface and provide their own draw() implementations.

In the main method, we have created instances of Circle and Rectangle, called the draw() method on each object, and the associated messages are printed on the console.

The above example code shows full abstraction using interfaces. The Drawable interface defines the abstract behavior (draw()), and concrete classes implement that behavior with their own specific logic.

5. By using interface, we can achieve the functionality of multiple inheritance. Look the at below example code.

Program code:

// Interface definition for behavior 1
interface Behavior1 {
    void performBehavior1();
}

// Interface definition for behavior 2
interface Behavior2 {
    void performBehavior2();
}

// Class implementing both interfaces
class MyClass implements Behavior1, Behavior2 {
    @Override
    public void performBehavior1() {
        System.out.println("Performing Behavior 1");
    }

    @Override
    public void performBehavior2() {
        System.out.println("Performing Behavior 2");
    }
}

public class Main {
public static void main(String[] args) 
{
   // Create an instance of MyClass
      MyClass myObject = new MyClass();

   // Call methods from both interfaces
      myObject.performBehavior1();
      myObject.performBehavior2();
  }
}
Output:
       Performing Behavior 1
       Performing Behavior 2

In this example, we have defined two interfaces, Behavior1 and Behavior2, each containing a single method declaration. The MyClass class implements both Behavior1 and Behavior2 interfaces and provides concrete implementations for both performBehavior1() and performBehavior2() methods.

In the main method of the Main class, we have created an instance of MyClass called myObject. Then, we have called both performBehavior1() and performBehavior2() methods on myObject.

As a result, we have achieved multiple inheritance in Java, and the output shows that both behaviors defined in the interfaces are successfully performed by the MyClass instance.

6. Interfaces allow us to achieve the polymorphism, which is one of the most important feature of OOPs concept. We can create references to an interface type and then assign objects of classes that implement that interface to those references. This provides flexibility and extensibility to our code, as we can interchangeably use different implementations of the same interface.

Program code:

// Interface definition
interface Shape {
    double area();
}

// Implementing classes
class Circle implements Shape {
    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

class Rectangle implements Shape {
    private double length;
    private double width;
    
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public double area() {
        return length * width;
    }
}

public class Main {
public static void main(String[] args) {
     // Polymorphism in action
        Shape circle = new Circle(5.0);
        Shape rectangle = new Rectangle(4.0, 6.0);

        System.out.println("Circle Area: " + circle.area());
        System.out.println("Rectangle Area: " + rectangle.area());
   }
}
Output:
       Circle Area: 78.53981633974483
       Rectangle Area: 24.0

In this example, we have defined an interface named Shape, which includes a method area() that calculates the area of a shape. Then, we have defined two classes, Circle and Rectangle, both of which implement the Shape interface. Each class provides its own implementation of the area() method.

In the main section, we have created instances of Circle and Rectangle and assign them to Shape references (circle and rectangle). This represents polymorphism, as we can treat objects of different classes that implement the same interface uniformly. Finally, we have displayed the calculated areas for the circle and rectangle on the console.


In this tutorial, we have explained how to use an interface in realtime Java application or project. Hope that you will have understood the basic concept of using interface in Java with realtime examples. In the next, we will learn nested interface in Java with the help of examples. If you like this tutorial, please share it on the social networking site for your friends.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love