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/[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:
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.