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

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?

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.