r/javahelp • u/The_King1337 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
r/javahelp • u/The_King1337 Intermediate Brewer • Jun 19 '13
I've recently learned about interfaces, but when would I actually use them? Thanks!
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
I can instead just do
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.