Why Use Interface in Java or Object Oriented Programming

Many times, I have seen questions like why should we use interface in Java, if we can not define any concrete methods inside interface? Or even more common, What is the real use of interface in Java? I can understand beginners asking this question, when they just see name of the method inside 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 of this is lack of experience in really modelling something real in program using object oriented analysis and design. In this article, I will try to answer this question and give you couple of reason to use interface in your code. If you have good understanding of Object oriented basics e.g. Polymorphism, then you know that it allows you to write flexible code. Interface or abstraction are key to achieve polymorphism, when a caller use interface for calling a method, he introduce 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 going to get this flexibility, if you use concrete classes for calling methods, we will see this in more details in next section. Also Programming for Interfaces, is also well recognized and one of the key object oriented design principle for coding. Another use of interface in Java is that, it opens new opportunities for other goodies e.g. design patterns. Lot's of design patterns are heavily relied on interfaces and Polymorphism e.g. Decorator, Composite, Proxy or Adapter pattern, all implements same interface, as there target, and because they are based on interfaces, they can be used interchangeably.



Use Interface for Flexibility and Polymorphism

As I said, polymorphism is powerful and provides flexibility and dynamic behaviour to your code. In order to take use of Polymorphism, you can either use interface or abstract class in Java. Interface provides 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 e.g. HashMap

If you look closely, you will find that, most of the time we use methods from interface. For example, here we are using get() method from Map interface, you could definitely write following code in terms of HashMap or Hashtable, but then you switched to another implementation e.g. ConcurrentHashMap, you need to change your code. Here, we are using Map interface for getting Employee object from Cache, which can be any valid Map implementation, including HashMap, Hashtable, or ConcurrentHashMap. On 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.


Use Interface in Java to accommodate Design patterns

Why use Interface in Object Oriented Programming
If you are familiar of famous GOF design patterns than you know that most of the behavioural pattern use Polymorphism for dynamic behaviour, e.g. Decorator pattern, implements same interface as the object, which it decorates. If you don't use interface, it would be impossible to incorporate design patterns e.g. if your method accept concrete type, rather than abstract type, then you can not pass anything else to them. You not only lose flexibility but also runtime behaviour enrichment. Similarly, Composite pattern also uses same interface as object it contains, and this allows caller to deal with a normal object or composite object in same way, had they don't use interface, it wasn't possible. Proxy and Adapter design pattern also relies on higher level abstraction e.g. interface or abstract class, to provide added behaviour. In short, interface is not just a good coding practice, it also open path to incorporate other best practices in your code.


Use Interface to help Unit Testing

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 start depending upon interfaces than implementation, which makes unit testing extremely easy. For example, a code which is using Database can not be tested in isolation, until  database is available, but if same code is using interface to interact with database layer (DAO design pattern), you can always provide a dummy or mock object to mimic database calls. By using 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 best way to introduce abstraction in your design. Real use of interface is to improve code quality by allowing modules to depend upon higher level of abstraction, which is less likely to change than lower level concrete classes, which is more likely to change. Use of interface also opens opportunities for using tried and tested Java design pattern and immensely helps in Unit testing as well. Most importantly, use of interface will give you different level of thinking and probably it's one step in mastering object oriented analysis and design.

2 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.

Post a Comment