Hello:) Most of us feel confused about the usefulness of interfaces at first times. There are questions like “Why do we need interfaces? “, “What is an advantage of using interfaces? “ and etc. In this blog, we will try to find the answers to these questions.
Let’s begin with a simple example. Assume that you are a student and you must prepare for an exam. You know there will be several things which will distract you during exam preparation. We can give examples like mobile applications and friends. Let’s describe them as a class:
I think you will agree with me that not every friend and every mobile application can distract you. For example, we can have hardworking friends. Or we can install useful mobile applications for our smartphones. So adding distract() method to these classes is not good. That is why let’s describe these distractions more clear :
You know this exam is very difficult and you don’t have much time. That is why you decide to print a list of distractable things with a header like “SAY NO!” and stick on the wall in your room. How can you achieve this?
At the first time, you can think about inheritance. Because if we create superclass named as “Distraction” and both of Facebook class and AdventureLoverFriend class extend it, we can collect all distractable things in one list. Because we can refer subclass object with superclass reference variable. Then we can do the needed operation on this list. But Facebook and AdventureLoverFriend cannot extend Distraction class. Because one class cannot extend more than one class in Java.
At this time we can see how the interface is useful. Let’s create an interface named “Distractable” to demonstrate this :
And implement it like the following:
As you see, interfaces allow us to define common behaviour that can be implemented by any class, regardless of its inheritance. Although AdventureLoverFriend class extends Friend class and Facebook class extends MobileApplication class, we can add common distractable behaviour to them by implementing Distractable interface. This means that we can “cut across” inheritance hierarchy to implement functionality as we see fit.
Since Java allows to refer implementation class object with interface reference variable, we can write following in ExamPreparation class:
So we print the list as we want:
Go through your entire Facebook news feeds again and again :/
I’m having a party this weekend and would love for you to come ^_^
And also consider that we only focus on their common distractable behaviour in printList method. We don’t care about their other behaviours. Because we look at them as Distractable object, not like Facebook or AdventureLoverFriend object in printList method. We can show it like this in code:
There are other great details about interfaces in Java. I tried to explain just one of them. Hope it will be helpful :)