Sunday, June 26, 2022

What is the Use of Interface in Java and Object Oriented Programming? [Answer]

Many times, I have seen questions like why should we use an interface in Java? If we can not define any concrete methods inside the interface the what is the user of the interface? Or even more common, What is the real use of the interface in Java? I can understand beginners asking this question when they just see the name of the method inside the interface and nothing else. It takes time to realize real goodness or actual use of interface or abstraction in Java or any object-oriented programming. One reason for this is a lack of experience in really modeling something real in the program using object-oriented analysis and design. In this article, I will try to answer this question and give you a couple of reasons to use the interface in your code. If you have a good understanding of Object-oriented basics like Polymorphism, then you know that it allows you to write flexible code.

Interface or abstraction is key to achieve polymorphism, when a caller use interfaces for calling a method, he introduces flexibility and dynamism in code, as that code will work with any implementation of that interface, not just the present concrete implementation.

You will never be going to get this flexibility if you use concrete classes for calling methods, we will see this in more detail in the next section. 

Also, Programming for Interfaces is also well recognized and one of the key object-oriented design principles for coding. Another use of the interface in Java is that it opens new opportunities for other goodies like design patterns.

Lots of design patterns have heavily relied on interfaces and Polymorphism like Decorator, Composite, Proxy, or Adapter pattern, all implement the same interface, as their target, and because they are based on interfaces, they can be used interchangeably.



3 Places to use interface in Java

Here are the three places where you should use interface in Java. I have also highlighted the pros and cons of using interface as well as what benefit you will get by using interface in a particular scenario. You can go through these scenarios to understand how to use interface in Java. 

1. Use Interface for Flexibility and Polymorphism

As I said, polymorphism is powerful and provides flexibility and dynamic behavior to your code. In order to make use of Polymorphism, you can either use interface or abstract class in Java. The interface provides the highest degree of abstraction.

 For example following code, which is based on interfaces, and an example of programming to interface than implementation principle is flexible enough to work with any Map implementation in Java.
Map cache = CacheFactory.getCach();
Employee emp = cache.get("EmployeeID");  
// this line depends upon interface Map, rather than concrete class
// like HashMap

If you look closely, you will find that most of the time we use methods from the interface. For example, here we are using the get() method from the Map interface, you could definitely write the following code in terms of HashMap or Hashtable, but then you switched to another implementation like ConcurrentHashMap, you need to change your code.

Here, we are using the Map interface for getting Employee object from Cache, which can be any valid Map implementation, including HashMap, Hashtable, or ConcurrentHashMap.

On a similar line, you should use interface as Type of method arguments and as return type. This makes your code flexible enough to operate on any implementation.




2. Use Interface in Java to Apply Design patterns in Java

If you are familiar with famous GoF design patterns then you know that most of the behavioral patterns use Polymorphism for dynamic behavior, like the Decorator pattern implements the same interface as the object, which it decorates.

If you don't use an interface, it would be impossible to incorporate design patterns like if your method accepts concrete type, rather than abstract type, then you can not pass anything else to them. You not only lose flexibility but also runtime behavior enrichment.

Similarly, the Composite pattern also uses the same interface as the object it contains, and this allows the caller to deal with a normal object or composite object, in the same way, had they don't use the interface, it wasn't possible. 

Proxy and Adapter design patterns also rely on a higher-level abstraction like the interface or abstract class, to provide added behavior. In short, the interface is not just a good coding practice, it also opens a path to incorporate other best practices in your code.

Why use Interface in Object Oriented Programming





3. Use Interface for Unit Testing in Java

Testing is a big concern for any Project. Project Managers, Technical lead and developers will always prefer a code which can be unit tested easily in isolation with other moving parts. When we use interfaces in our code, our method starts depending upon interfaces than implementation, which makes unit testing extremely easy.

For example, a code that is using Database can not be tested in isolation, until the database is available, but if the same code is using an interface to interact with the database layer (DAO design pattern), you can always provide a dummy or mock object to mimic database calls. By using the interface in your code, you get flexibility everywhere.


That's all on why you should use interface in Java. Though you can not define concrete methods, it's the best way to introduce abstraction in your design. The real use of the interface is to improve code quality by allowing modules to depend upon a higher level of abstraction, which is less likely to change than lower-level concrete classes, which are more likely to change.

The use of interface also opens opportunities for using tried and tested Java design pattern and immensely helps in Unit testing as well. Most importantly, the use of an interface will give you a different level of thinking, and probably it's one step in mastering object-oriented analysis and design.

Other Object Oriented Programming Tutorials you may like
P. S. - If you have any questions using interface in Java or pros and cons of each of them, feel free to ask in comments. If you need free resources to learn OOP and Java then you can also checkout these free object oriented programming courses for beginners.

3 comments :

SARAL SAXENA said...

just to add..

Interfaces are needed where you expect volatility in your program, points at which you anticipate change, points where your design needs to bend.

Implementation is fragile in this sense: it breaks quite easily. This is why subclassing isn't always the best solution, just as long-winded methods that implement some complicated behavior all by themselves are generally a bad idea.

Interfaces are more flexible and can deal with a lot more stress on the design of your program than implementation.

By introducing interfaces into your program, you really introduce points of variation at which you can plug in different implementations for that interface. Interfaces' primary purpose is abstraction, decoupling the "what" from the "how".


Interfaces are a way to make your code more flexible. What you do is this:

Ibox myBox=new Rectangle();
Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:

Ibox myBox=new OtherKindOfBox();
Once you get used to it, you'll find it's a great (actually essential) way to work.

Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:

myBox.close()
(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.


Interfaces are a way to make your code more flexible. What you do is this:

Ibox myBox=new Rectangle();
Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:

Ibox myBox=new OtherKindOfBox();
Once you get used to it, you'll find it's a great (actually essential) way to work.

Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:

myBox.close()
(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.


An example below shown..

One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :

class Animal
{
void walk() { }
....
.... //other methods and finally
void chew() { } //concentrate on this
}
Now, Imagine a case where:

class Reptile extends Animal
{
//reptile specific code here
} //not a problem here
but,

class Bird extends Animal
{
...... //other Bird specific code
} //now Birds cannot chew so this would a problem in the sense Bird classes can also call chew() method which is unwanted
Better design would be:

class Animal
{
void walk() { }
....
.... //other methods
}
Animal does not have the chew() method and instead is put in an interface as :

interface Chewable {
void chew();
}
and have Reptile class implement this and not Birds (since Birds cannot chew) :

class Reptile extends Animal implements Chewable { }
and incase of Birds simply:

class Bird extends Animal { }

Anonymous said...

First and formost reason of using Interface is working with abstraction rather than implementation. When you work with generic abstraction, you have a chance to swap implementation which gives flexibility to your program. In the long run, use of interface improves flexibility, maintainability, and performance of Java application? how come performance? because it allows you to develop new high performance implementation and swap them without chaning the client code. In short, you must code with interface e.g. use interface as type of variable, use interface in method parameter, use interface while extending or impelementing e.g. extend from Map not from HashMap.

Anonymous said...

Hey man I've a doubt. Why do we need an interface at all? Why can't we directly define the chew function in the reptile class and not in bird class?

Post a Comment