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

8

u/[deleted] Jun 19 '13

Hey it's you again!

An interface works as a promise. "I'll get you a car, let's work out the details later".

When you actually extend that interface and implement the methods, you need to stick to that promise.

So, when would you use them? Here's an example I did just the other day -

I was creating this simple game, and I needed to create 'things', all the 'things' had to have a sprite mapped to them, they also had to do things when they were hit, or when they hit something.

So I created this interface I called Entity.

An Entity has methods for getSprite(), onCollisionX(), onCollisionY(), gotHit(), hit(), moveY(),moveX(), amongst other things. When I pass around my Entity, it doesn't care if its a bullet, a goomba, a player, because every time I pass it around, those general methods I've promised to be there.

So when I'm resolving some collisions, I can just go through my entities, check if they collided with something, then I don't have to do all this

if( currentEntity.isCharacter() ) {
   // do stuff for when the character hits something
} else if ( currentEntity.isBullet()) {
   // do stuff for when the bullet hits something.
}

I can instead just do

attacker.hit(defender);
defender.gotHit(attacker);

And then my individual classes will live up to their promise and resolve their issues in whatever way is best, a bullet will take away HP and disappear when it hits something, and a character will stop moving if it hits something, but all of these are broken into their own instances of the Entity interface, instead of lumped together into a weird pile of logic.

So, I guess in very basic, over simplified terms - you'd use an interface when you want multiple things to have the same types of actions, but respond differently.

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/The_King1337 Intermediate Brewer Jun 20 '13

Thanks a bunch! You've explained it better and in more depth than anyone!

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.

3

u/snot3353 COMPUTERS!!! Jun 19 '13

Probably the most significant difference is that a class can only extend one other class whereas it can implement any number of interfaces. On top of that, an interface is always 100% abstract. You cannot implement any of the methods to have a default concrete implementation whereas with a class or abstract class you can have either all the methods have implementations or some concrete and some abstract.

1

u/[deleted] Jun 19 '13 edited Jun 20 '13

Inheriting from a class limits your flexibility and says "This class is a subtype of this other class." Well, that may not be what you want. Implementing an interface just binds you to a 'contract' that your class is capable of acting a certain way (i.e. it implements certain methods). A class can implement any number of interfaces. To use a simplistic example, a Dog class can be Pettable, Walkable, Feedable, etc.

1

u/Otroletravaladna Extreme Brewer Jun 19 '13

An interface works as a promise. "I'll get you a car, let's work out the details later".

An interface is not a promise: it's a contract! A promise can turn into "yeah, I told you I would get you a car, but now I need $15 for gas... Oh, and a mobile phone too". A contract is more like "I'll get you a car if you give me a real car brand and model. If you ask for my services without giving me a valid, available car model I'll fill an 'invalid/unavailable car model' form and give it to you as a formal notification. Any additional requirements not stated in this contract are none of your business and you won't need to care about them.".

With that contract in mind, you can interact with car vendors through a clearly defined "protocol", and you can enforce that any vendor willing to provide services for you must sign that contract and act strictly under its terms. This way your business doesn't need to "marry" with a particular vendor.

2

u/[deleted] Jun 19 '13

I'll use an example involving the Comparable interface. Say you create several objects that all implement Comparable.

You can then create Lists, ArrayLists, etc and ensure that all objects that are contained in that list implement Comparable (and therefore have compareTo, which you use to insert items in an ordered fashion). This would be achieved by saying something akin to:

ArrayList< E extends Comparable<E> > list = new ArrayList<E extends Comparable<E> >();

That's the instance that I use it most frequently in. It can be changed so that Comparable is some sort of custom written interface, thereby ensuring that only objects that implement a certain interface belong in a certain list.

2

u/DLFCN Jun 19 '13

I would implement an interface to avoid writing duplicate code/methods in multiple classes. Makes things easier if you decide to change something, you only have to change one method in your interface rather than however many classes have that method in it.

So... For example your making an Alien Space Shooter game. Your PlayerShip.class and EnemyShip.class may implement an interface called Movement that deals with moving an object around screen. The interface would have methods such as moveLeft(), moveUp(), rotate(), etc. that both payer ship class and enemy ship class call often. Interfaces can also store information, for example your player ship and enemy ship will most likely have an X and Y coordinate on screen. In your interface you make and int x and int y, and have your movement methods in the interface manipulate those ints and then retrieve those ints with a get method in your interface.

Some good reading: http://docs.oracle.com/javase/tutorial/java/IandI/index.html

2

u/dudleydidwrong Jun 19 '13

One practical issue is that you can only inherit from one class. Some languages lik C++ allow multiple inheritance, but experience suggested that unrestrained multiple inheritance can take you to hell in a handbasket very quickly. A set of guidelines were developed fo C++ programmers to help keep them out of the deep end of the multiple inheritance cess pool. One of these guidelines said to only inherit data fields from one class; all the other classes should be pure virtual classess. Java formalized this concept to an interface. So in Java you can extend one full calss, but you can use as many interfaces as you want.

I think the best way to learn about interfaces and motivations for using them is to learn about GUI and event-driven programming. Swing uses just s about every feature of classes and interfaces. You may not like Swing for other reasons, but it is useful as a learning tool.

0

u/Stromovik Jun 19 '13
  1. Callbacks

  2. Calling classes with unknown logic , but enforcing the implementation of set of methods. While in theory you could write without interfaces. It will be a nightmare to read.

0

u/[deleted] Jun 19 '13

[deleted]

2

u/hadihaha Jun 20 '13

Thankyou! I have just finished a semester of OO Java and only now has it clicked properly!

1

u/AS1LV3RN1NJA Sep 15 '13

Sorry I'm late to the thread (going through saved links).

I'd just like to say, this is probably the clearest explanation I've seen, thanks.