DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • OOP in Java: Polymorphism and Interfaces
  • The Role of Functional Programming in Modern Software Development
  • Best Ways to Write Clean and Quality Python Code
  • A Guide to Constructor Chaining in Java

Trending

  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • Debugging Core Dump Files on Linux - A Detailed Guide
  • Automatic Code Transformation With OpenRewrite
  • How to Format Articles for DZone
  1. DZone
  2. Coding
  3. Frameworks
  4. Why Do We Need an Interface in OOP?

Why Do We Need an Interface in OOP?

There are many reasons for including interfaces in OOP. Here's one major advantage of using interfaces in Java.

By 
Vusala Hasanli user avatar
Vusala Hasanli
·
Updated Mar. 20, 19 · Analysis
Likes (14)
Comment
Save
Tweet
Share
34.4K Views

Join the DZone community and get the full member experience.

Join For Free

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:

class Friend {

    public void askHelp(){
        System.out.println("I will do my best to help you!");
    }
}

class MobileApplication {

    public void installApp(){
        System.out.println("The installation is complete.");
    }
}


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:

class AdventureLoverFriend extends Friend{
   public void getAdviceAboutTravel(){
        System.out.println("I will help you travel better :)");
   }
}

class Facebook extends MobileApplication{
    public void connectPeople(){
        System.out.println("Stay in touch with friends from all over the world!");
    }
}


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:

interface Distractable{
    void distract();
}


And then, let's implement it as follows:

class AdventureLoverFriend extends Friend implements Distractable{

    public void getAdviceAboutTravel(){
        System.out.println("I will help you travel better :)");
    }

    @Override
    public void distract() {
        System.out.println("I’m having a party this weekend and would love for you to come ^_^");
    }
}

class Facebook extends MobileApplication implements Distractable{

    public void connectPeople(){
        System.out.println("Stay in touch with friends from all over the world!");
    }

    @Override
    public void distract() {
        System.out.println("Go through your entire Facebook news feeds again and again :/");
    }
}


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:

class ExamPreparation {
    public static void main(String[] args) {
        List<Distractable> distractableList = getListOfDistractableThings();

        System.out.println("\t\t\t\t\t\t  SAY NO! ");
        printList(distractableList);
    }

    public static void printList(List<Distractable> distractableList){
        for(Distractable distractableThing: distractableList){
            distractableThing.distract();
        }
    }

    public static List<Distractable> getListOfDistractableThings(){
        List<Distractable> distractables = new ArrayList<>();

        Distractable facebook = new Facebook();
        distractables.add(facebook);
        Distractable adventureLoverFriend = new AdventureLoverFriend();
        distractables.add(adventureLoverFriend);

        return distractables;
    }
}


So, we print the list as we want:

                         SAY NO!
Go through your entire Facebook news feeds again and again :/
I’m having a party this weekend and would love for you to come ^_^


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:

Distractable facebook = new Facebook();
facebook.connectPeople(); //doesn't compile


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!

Interface (computing) Object-oriented programming

Published at DZone with permission of Vusala Hasanli. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • OOP in Java: Polymorphism and Interfaces
  • The Role of Functional Programming in Modern Software Development
  • Best Ways to Write Clean and Quality Python Code
  • A Guide to Constructor Chaining in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!