Thursday, July 13, 2023

What is the actual Use of interface in Java?

An interface in Java has remained a complex topic for many beginners to understand. The first thing which puzzles many programmers is the fact that you cannot define any method inside interface, it a just declaration. By rule, all method inside interface must be abstract (Well, this rule is changing in Java 8 to allow lambda expressions, now interface can have one non-abstract method, also known as a default method). So, if you can't define anything, Why we need an interface?  what's the use of an interface, if we are anyway going to write a class and override them to provide behaviour, Can't we declare those methods inside the class itself without using interface etc. Well, if you are thinking in terms of behaviour then you are really missing the point of interface.

I think one has to read Effective Java, to understand best use of interface. Interface is great to declare Type, they promote code reusability, and they are the real driver of polymorphism in Java.

The interface also allows multiple inheritance in Java, which makes it possible for a class to become Canvas, as well as EventListener, which is used to draw graphics as well as to to process events. 

In this post, I will share few points, which will help you to understand what is the actual use of interface in Java. By the way, if you are confused between abstract class and interface, then you may want to read my previous post on difference between interface and abstract class in Java




Why we need Interface in Java?

There are several reasons, an application developer needs an interface, one of them is Java's feature to provide multiple inheritance at interface level. It allows you to write flexible code, which can adapt to handle future requirements. Some of the concrete reasons, why you need interface is :

1) If you only implement methods in subclasses, the callers will not be able to call them via the interface (not common point where they are defined).

2) Java 8 will introduce default implementation of methods inside the interface, but that should be used as exception rather than rule. Even Java designer used in that way, it was introduced to maintain backward compatibility along with supporting lambda expression. All evolution of Stream API was possible due to this change.

3) Interfaces are a way to declare a contract for implementing classes to fulfil; it's the primary tool to create abstraction and decoupled designs between consumers and producers.

What is the Actual Use of interface in Java?



4) Because of multiple inheritances, interface allows you to treat one thing differently. For example a class can be treated as Canvas during drawing and EventListener during event processing. Without an interface, it's not possible for a class to behave like two different entity at two different situations. 

Here is an example of how interface supports multiple inheritance in Java

interface Canvas{
  public void paint(Graphics g);
}

interface EventListener{
  public boolean process(Event e);
}

pubic class Game implements Canvas, EventListener{

 @Override
 public void paint(Graphics g){
   g.drawLine(Color.RED);
 }

 @Override
 public boolean process(Event e){
   KeyCode code =  e.getKeyPressed().getCode();
 }

}

5) Interface is key to API design. In fact, a smaller interface like Comparable, Runnable, Callable makes the core of Java API. Though great care is required while designing and publishing an interface, because once published, you can not change the interface without breaking up all your clients, i.e. classes which have implemented your interface. 

In an extreme case, from Java 8 onwards, you can use the default method to rescue, but as I said, it should be the exception to the rule.

Why we need interface in Java


6)  "Programming to interface than implementation" is one of the popular Object-oriented design principles, and the use of interface promotes this. A code written on the interface is much more flexible than the one which is written on implementation.

7) The use of interface allows you to supply a new implementation, which could be more robust, more performance in the later stages of your development.

In short main use of the interface is to facilitate polymorphism. the interface allows a class to behave like multiple types, which is not possible without multiple inheritances of class. It also ensures that you follow programming to the interface than the implementation pattern, which eventually adds a lot of flexibility in your system.


Other Java programming and OOP tutorials You may like

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.


14 comments:

  1. Point #3 says it all.

    Java Interfaces are simply put, contracts. They ensure all implementers of the interfaces do so in a inform manner.

    It's about time they got beefed up a little. Other languages that use mixins etc are leaving Java for dead.

    ReplyDelete
  2. I think real use of interface is in unit testing. Code which are written using interface are loosely coupled and easier to test becaues you can easily supply a mock or stub implementation instead of real one. Since unit testing is very important for delivering qulaity software, its better to use interface in Java then class, especially for type declation.

    ReplyDelete
    Replies
    1. yes....its play important role in unit test

      Delete
  3. I still dont understand interfaces! do impart different behaviours to a class cant we just write different methods ? and how does interfaces support code reusability when interface dont have any definition (only declaration) and the fact that anyways we've to write a definition in the class which we are using to implement interfaces ? whats the use when you are and you have to define the method in the implementing class ??? please explain with a simple code as to why we need interfaces and what actually they do ?
    Thanks!

    ReplyDelete
    Replies
    1. it is cool what you said when we are looking at a single class. but when it comes to more than one class and you want to maintain a certain level of agreement among them then it plays its role of tellling them to implement methods in a way that is defined in the interface and not go out of that way but also achieve their logic inside those methods. hence what we achieved was we maintained the common signature among the classes of a same type(eg: PermanentEmployee and ContractEmployee are classes of Employee type) and yet have their own logic different from the other class of the same type.

      Delete
  4. The reusability comes when it comes to client classes, they need not be changed when an implementation in the interface changes for example the oracle driver classes when we migrate the DB from one version to another we just need to update our drivers and the client code need not be changed when we change the DB this is where reusability comes into picture

    ReplyDelete
  5. Pls explain the real life use of user defined interface, pls pls pls don't explain the benefits of system defined interface e. g paint, actionlistener etc etc..

    ReplyDelete
    Replies
    1. The truth has never been spoken, all hail python!

      Delete
  6. i agree in the comment section . re usability , multiple inheritance et . r useless. interfaces r just functionality or contract which a class provides to other non related classes. it helps in better encapsulation .

    ReplyDelete
  7. Apart for all the benefits mentioned above, the core advantage is decoupling that leads to testability and DI.

    ReplyDelete
    Replies
    1. Indeed, decoupling is the most important thing which provides flexibility to run different code at different time, improving test-ability and DI.

      Delete
  8. Please explain this interface just provide us funtion declarations how it gets too much importance in java although we must define all function behavior in subclass ..

    ReplyDelete
    Replies
    1. @Unknown, Flexibility is the keyword, interface provide the much needed flexibility, which means a single line of code like a call to interface method can do different things in different context, I mean when a different implementation is passed. For example

      Executor.execute()

      can run different code depending upon different implementation.

      Delete
  9. In a nutshell, it is just to make your work more neat.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.