Most of us feel confused about the usefulness of interfaces at a first glance. We have questions like “Why do we need interfaces?” and “What is the advantage of using interfaces?” 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 need to prepare for an exam. You know that there will be distractions during your exam preparation. We will use mobile applications and friends as our example. Let’s describe each as a class:
I think most would agree with me that not every friend and mobile application can be a distraction. For example, we can have hardworking friends. Or, we can install useful mobile applications on our smartphones. So, adding the distract()
method to these classes is not good. That is why we need to describe these distractions in greater detail:
You know that your upcoming exam is going to be very difficult and you don’t have much time to prepare. This is why you decided to print a list of distractions with headers like “SAY NO!” and stick them on the wall in your room. How can you achieve this?
Well, you can think about inheritance. Because if we create a superclass named Distraction
, and both the Facebook
class and AdventureLoverFriend
class extend it, we can collect all distractable things in one list. Because we can refer to the subclass object with the superclass reference variable, we can conduct the needed operation on this list. But Facebook
and AdventureLoverFriend
cannot extend the Distraction
class. This is because, in Java, one class cannot extend more than one class.
At this time, we can see how the interface is useful. Let’s create an interface named Distractable
to further demonstrate this:
And then, let’s implement it as follows:
As you can see, the interfaces allow us to define common behavior that can be implemented by any class, regardless of its inheritance. Although the AdventureLoverFriend
class extends the Friend
class and the Facebook
class extends the MobileApplication
class, we can add common distractable behavior to them by implementing the Distractable
interface. This means that we can “cut across” the inheritance hierarchy to implement functionality as we see fit.
Since Java allows us to refer implementation class objects with interface reference variable, we can write the following in theExamPreparation
class:
So, we print the list as we want:
Also, consider that we only focus on common distractable behavior in the printList
method. We don’t care about other behaviors because we look at them as a Distractable
object, unlike the Facebook
or AdventureLoverFriend
object in the printList
method. We can show it like this in the code:
There are many other reasons why we need interfaces in Java. In this post, I tried to explain one of the more important concepts. Hope it was helpful!