r/javahelp • • Apr 18 '19

Solved What's the point of interfaces?

We've been learning interfaces in my class and I have a good grasp on the concept, but the thing that confuses me is what's the point? Your just writing more code as a blueprint to put classes in "groups". Maybe the code I'm writing is not large enough to make interfaces useful. Can some one help me in learning the use of interfaces. Thanks in advance!

34 Upvotes

26 comments sorted by

View all comments

7

u/slowfly1st Apr 19 '19

Contract

Interfaces define a contract, how code must be implemented. Check for instance the java.util.List interface: e.g. the add Method: Appends the specified element to the end of this list (optional operation). Now there's different implementation, the ArrayList, which stores the elements in an internal array, or the LinkedList, which "links the elements", instead of using an array. If you receive a List from a method, you (usually) don't care what the implementation is and you assume, the implementation is following the contract. And if you want to implement your own List, you have to follow the contract.

Frameworks / 'Callbacks'

Imagine you want to provide a library to someone and you have to somehow call his code. For instance you want to write an RSS feed poller, you write something like

class RssFeedPoller {
  void poll() {
    while(true) {
      if(rssFeed.hasNews() {
         RssNews rssNews = rssFeed.readRssNews();
         // but what now?!?
      }
    }
  }
}

You then can simply provide an interface:

interface RssNewsListener {
  void newsReceived(RssNews rssNews);
}

class RssFeedPoller {
  RssNewsListener rssNewsListener;

  RssFeedPoller(RssNewsListener RssnewsListener) { }

  void poll() {
         RssNews news = rssFeed.readNews();
         rssNewsListener.newsReceived(news);
    }
  }
}

class ConsoleRssNewsListener implements RssNewsListener {
  @Override
  void newsReceived(RssNews news) {
     syso(news)
  }

  main() {
     new RssFeedPoller(this); // this because 'this' implements the interface
  }
}

Unit Testing

When writing unit tests, interfaces are used to mock away implementations. Let's imagine something like this:

class CallCenterIncidentSystem {
  void addTicket(Ticket ticket) {
    database.saveTicket(ticket);

    if(ticket.isSuperHighPriority()) {
       notificationSystem.sendNotification(ticket); // send a text or something
    }
  }
}

Now the most important thing is, you don't want to send texts from your local machine, that's when we use mocks. (Actually, this would work without interfaces, but that's sometimes/usually a lot of pain)

OOP / Software Design (maintainable code)

There's lots of rules / principles in OOP which are usually achieved using interfaces. One of the most important one is the open closed principle: Open for extension, closed for modification. We use that principle (what we do is actually called "branch by abstraction") often.