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!
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