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

34

u/Talulabelle Apr 18 '19

The short-short, practical, answer is 'So you can have different types in the same collection'.

Let's say you have a bunch of different objects, but you want to put them all in a list, and then tell every object in the list to save it's self.

Without an interface, you'd have to have a different location for each object, and a huge method that finds every object that needs to be saved, and call it's individual save method.

If you just 'implements savable' and guarantee that, regardless of the type, it will implement the 'public void save();' method, you can put everything in a 'List<Savable> thingsToBeSaved' when you create it, and then have a method that calls 'save()' on everything in the list.

Tl;Dr; It lets us work with different classes as though they were the same type for, for a single, specific, purpose.

10

u/ProHoyah Apr 19 '19

Wow that just gave me the "ah ha" moment thanks for the help!

5

u/Talulabelle Apr 19 '19

Great! I figured you just needed a simple example, if you already knew the theory.

0

u/Chuuy Apr 21 '19

This answer completely misses the true importance of interfaces. Read this answer: https://www.reddit.com/r/javahelp/comments/bereu8/whats_the_point_of_interfaces/el8nfg9/?utm_source=share&utm_medium=ios_app

1

u/Talulabelle Apr 22 '19

OP states he already understands the theory of how they work, but wasn't able to understand why anyone would use them. I wasn't trying to teach theory, just give a simple example of a problem most people can at least imagine running into, and how one might solve it with the help of interfaces.

This answer doesn't 'miss' anything, OP stated clearly that they had that part of the puzzle.

1

u/Chuuy Apr 22 '19

The first sentence of your answer is objectively wrong. If you're going to say something like that, at least say it with a caveat. You're guiding him in the wrong direction.

1

u/Talulabelle Apr 22 '19

The short-short, practical, answer

That's not a caveat?! That's EXACTLY what I did!

I was trying to give him a very short, very practical, very simple and blunt use for the technique, that might make a light bulb go on.

If you ask 'How does the circulatory system work?', and someone says 'Well, the short-short, practical, answer is that the heart pumps blood to move oxygen around', you don't turn around and say 'That's wrong! It does so much more! You're lying!'

It's just an example a five year old could follow, and I went that direction specifically because everyone explains these things in exactly the same way, in every text and comment ... because that's the 'right' answer, but if someone isn't getting it, and they tell you 'I've read the book, I'm not getting it', you don't just repeat the book to them.

I figured what this person needed wasn't the whole story, or the theory, but just a super-simple idea of what you can do with them that they could hold on to, to get a foot in the door of understanding why you'd use them. Once you see it as a tool for one problem, and you understand why it works, it's much easier to see how it applies to more problems.

My answer isn't wrong, it's just an illustration of a short-short, practical, application that I hoped they'd be able to grasp.

OP literally upvoted it saying 'the light came on', and they started to understand why they're important.

When someone says 'I know the theory', they're literally saying 'Don't just re-iterate the book answer'. The book answer is still out there for them, now that they have a foot in the door to understanding it.

0

u/Chuuy Apr 22 '19

You said:

The short-short, practical, answer

Next time, try:

A short-short, practical, example

1

u/Talulabelle Apr 22 '19

Yeah ... I'm going to take advice from the guy who pedantically posts on other people's comments like it's his job, and constantly gets into Reddit arguments about stupid shit.

I looked at your history. Commenting on shit where you try to tell people they're wrong, while adding nothing, and coming away looking like an idiot is how you live your life.

Next time, if your entire argument is 'you said answer, and I think you meant example', try just shrugging, and realizing that you're picking apart a days old answer that most people found helpful, and maybe they were able to glean the meaning of the post by not being overly pedantic children while reading it.

Please go away now.

0

u/Chuuy Apr 22 '19

It's not pedantic. The message I got from your post was that the only reason you'd use interfaces would be for collections. You completely glossed over other practical applications. If you seriously can't think of other real-world examples of how interfaces are useful, that's embarrassing.

I'm a lurker. I usually only post if I disagree with what someone said. Sue me. I don't care about karma, I don't have the time to provide a lengthy explanation of every single opinion I have. That's why I'm a fucking lurker, I don't care.

But your top voted answer sucks compared to the other answers in this thread. Maybe English isn't your first language? Idk. It's not pedantic. You phrased your answer in a way that made it seem like collections of different objects were the only reason you'd need an interface.

1

u/Talulabelle Apr 22 '19

The message I got from your post was that the only reason you'd use interfaces would be for collections.

Well, that's really sad and I'm sorry for you. Being unable to follow a dumbed down post must make life really hard. I can see why you'd be frustrated all the time, and constantly trying to feel smart by posting this kind of thing.

I'm sorry kitten, feel better. You probably won't get any smarter, but I'm sure you'll find someone who loves you anyway.

1

u/Chuuy Apr 22 '19

Lmfao. That's straight up what you said:

OP:

What's the point of interfaces?

You:

The short-short, practical, answer is 'So you can have different types in the same collection'.

That's so short-sighted it's hilarious.

A lot of people in the field of computer science struggle with English. You're one of them.

→ More replies (0)

0

u/[deleted] Apr 19 '19

[deleted]

2

u/FrenchFigaro Software Engineer Apr 19 '19

It would, but only up to a point. Java doesn't support polymorphism the way C++ does for example. A class can only inherit from a single super class.

As pointed out in u/talulabelle 's answer, interfaces guarantee compliance to behaviour, and leave the specifics of that compliance to the developper, and a class can implement several interfaces. In their example, they imagine a Savable interface which guarantees the existence of a save() method. But a class implementing Savable could also implement Cloneable, or Sortable.

IE: when programing against an interface, you don't care how the object is saved, you only care that it can be saved in a predicitble manner (by using the save() method)

1

u/Talulabelle Apr 19 '19 edited Apr 19 '19

Yes, but with some limitations. First, you can only inheret from one parent at a time. So, you'll probably end up creating some kind of 'base' class. Now you have to decide, do you have some inheritance gymnastics where a 'savable' class inherits from a 'resettable' class, vice versa, or you just make a junk class to hold all your methods that don't fit anywhere else.

Do you really want everything to inheret from 'savable' if that's the only thing they have in common, and no two classes will save the same way? How does that benefit you?

Imagine inhereting behavior you almost certainly don't want from a junk class? Or defining a whole hierarchy of classes that only inherit from one another because you need all those methods eventually.

So, why doesn't Java just do multiple inheritance instead?

Well, we don't need a 'savable' class defined. If anyone gets the bright idea to create a 'save' method in the base class, and you forget to override it, that's just going to cause problems.

Multiple inheritance often causes more problems than it solves. If you have two classes that both implement 'save()' (your savable class and whatever you actually want to inherit from both will), which one 'wins' and gets executed in the child class? If your design changes, your inheritance house of cards changes too.

Using an interface for things you're going to override anyway guarantees there's only one option at execution.

Tl;Dr Yes, but poorly.

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.

3

u/prashant_jaswal Apr 19 '19

Interface is a specification. And the vendor provides the implementation.

For example - An ATM machine has some features like withdraw, deposit, balance enquiry and many more. While designing these features, ATM service provider described these methods in an interface.

Public interface ATMService{

void withdraw(double withdrawing Amount,long accountNo);

void deposit (double amount,accountNo);

double getBalance(account No); }

And they are expecting it's implementation from some vendor.

The reason it is said code to interface rather than the implementation, is because we are invoking the method through interface, later on if there is some changes in the implementation or if first implementation was in .net and now they want in JAVA,only the implementation will be changed, ATMService won't be bothered about it as it is communicating with interface and not the implementation.

And Also, you have implement multiple interfaces in your class but you can extend only one class.

Hope it helps

2

u/[deleted] Apr 18 '19

A simple example is having different versions of the same class that retrieve data.

Let’s say you have a book data access class and so you create an interface that has methods for creating, updating, editing, and deleting books.

You implement the interface and have this implementation get the data from the database through sql queries.

Some time goes on and you now want to get the book data from a restful api. Well you can just have a new class implement the interface and now in the methods you connect to a rest api instead of the database using sql. You can be sure you’ve implemented the correct methods and you can simply switch out the original implementation for the new one, and whatever class was using your original implementation shouldn’t notice a difference, even though your new implementation gets the data in a completely different way. Everything that was using your original implementation will use the new one in the exact same way.

Same methods, different ways of implementing them.

2

u/ZeroGainZ Apr 18 '19

The same reason why everyone likes USBs, because whatever the class is, as long as it meets the interface, communication can occur between the two in a standard defined way.

2

u/Daedalus9000 Java Developer Apr 19 '19

Simply put, it separates how the pieces of a program interact with each other (interface) from how each piece of a program does its job (implementation). When I was in school I felt exactly the way you did, but once you start working on a sprawling and complex code base, it becomes much more clear why interfaces are a necessity.

2

u/age_of_empires Apr 18 '19

Its java's form of multiple parents

1

u/[deleted] Apr 19 '19

Maybe the code I'm writing is not large enough to make interfaces useful.

Without a doubt this is part of it. As the code gets larger it starts to make sense. The size code you are writing in school usually is just enough to show you understand the mechanics of it but is so small the "why" of things often gets lost. I recommend looking into some open source projects. It can help to start understand how things work with a larger code base.

1

u/Shadow_Mite Apr 21 '19

The simple way we learned it was through taxonomy. Public class dog interfaces mammal. Dog is it’s own class but it inherits everything from the mammal interface. In short, it’s one way to achieve polymorphism

-2

u/wsppan Apr 18 '19

Multiple inheritance and API contract.