Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven’t ever really been exposed to good explanations of interfaces or when to use them.
I am talking about interfaces in a context of interfaces vs. abstract classes.
Interfaces allow you to program against a ‘description’ instead of a type, which allows you to more-loosely associate elements of your software.
Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says ‘is that USB?’ and you say yes – all set. It doesn’t matter the size of the flash stick, nor the maker – all that matters is that it’s USB.
In the same way, interfaces allow you to generisize your development. Using another analogy – imagine you wanted to create an application that virtually painted cars. You might have a signature like this:
This would work until your client said ‘now I want to paint trucks’ so you could do this:
this would broaden your app… until your client said ‘now I want to paint houses!’ What you could have done from the very beginning is created an interface:
…and passed that to your routine:
Hopefully this makes sense – it’s a pretty simplistic explanation but hopefully gets to the heart of it.