r/javahelp • Intermediate Brewer • Jun 19 '13

When would I use interfaces?

I've recently learned about interfaces, but when would I actually use them? Thanks!

17 Upvotes

16 comments sorted by

View all comments

Show parent comments

2

u/The_King1337 Intermediate Brewer Jun 19 '13

Thank you, I understand that. But why not just use a class with those methods and override them as necessary?

4

u/[deleted] Jun 19 '13

My reddit seems to be broken or something, nothing is showing up, so hopefully you receive this.

There's no reason you couldn't use a class (at least for simpler examples, more complex examples, an interface helps you avoid the deadly diamond of death - more here http://en.wikipedia.org/wiki/Multiple_inheritance ), but then, why not use assembly, when you can create equally powerful programs? Languages provide features for you to use, you never want someone to instantiate an 'Entity', you want them to use it. There's a certain abstractness behind an 'Entity', or in a racing game, a 'Car' - you need to be more specific to have it mean anything in your context. Interfaces provide you with a manner to say "here's an idea for a thing, but to actually get that thing, you have to flesh it out". Accelerating on different racecars is different, and so you can't just say 'Car' in Gran turismo, you have to select a type of car. Since there's no need to instantiate a car, you maybe create an interface, so everyone knows not to create an instance of that object.

In summary: readability and safety. Someone reading your code will immediately understand what it is, and somebody, even you, writing your code will never accidentally create an instance of that interface and expect it to work.

1

u/Zokkar Jun 20 '13

What about an abstract class?

1

u/[deleted] Jun 20 '13

Do you mean when you would use an abstract class, or are you asking what an abstract class is?

Basically, an abstract class is an interface, but that has some of its functions implemented. So it's kind of like, you guys all have to do these functions, but getX() will pretty much always return this.x, so why have each of you implement that? An abstract class will define common functions so that it's child classes can, if they want, inherit them, but they don't have to.

This is useful so you can follow DRY principles - Don't Repeat Yourself, which makes things less prone to error; it also gives a default implementation for things that make sense to have them, so that your new class can be up and running much quicker, and then later you can tweak some functions to be exactly how you like.