tags:

views:

29

answers:

3

My knowledge of interfaces is quite limited.

I'm trying to understand them better. What purpose exactly do they serve and when would it be advisable to use them?

Thanks

A: 

You are asking a question that fills multiple chapters of most OO text books. I think the best way to answer questions like these is to provide resources, so:

http://en.wikipedia.org/wiki/Interface_(Java)

http://livedocs.adobe.com/flex/3/html/help.html?content=04_OO_Programming_10.html#135768

Or your favorite OO programming book.

In a nutshell, implementing an interface is a little bit like extending a class, except that the interface does not implement the methods you inherent, your class must do that itself. Also, you can implement multiple interfaces. For example, I can create an abstract class Animal and then Flyable and Quackable interfaces. Now class Bat extends Animal and implements Flyable. Class Duck extends Animal and implements both Flyable and Quackable. Class DuckCall can also extend Quackable, etc. You can pass objects to methods based on their interfaces also.

Wade
A: 

The way I see it, interfaces are used in a similar way to electrical connectors: they define the signals that go in and out of a device so that you don't have to care what exactly is plugged in as long as it respects those rules.

For example, take an mp3 player and it's headphone jack. The engineers that build your mp3 player don't have to care what kind of headphones you will be using on it, and that is possible because of the jack interface. They program your player against that interface, and then any type of headphones will work as long as they have the jack with the right size. They can even be speakers, they still work (isn't that cool?).

Furthermore, nobody forbids you to plug in something else in the jack socket, as long as it has a jack plug (it implements the interface). You are free to interpret the signals in whatever way you want, and you can for example build a device that changes color instead of playing music.

OOP interfaces work in a similar way: if you require an interface for the objects that are passed as parameter for a method, the caller can send you any implementation for that interface, and the objects that are sent can interpret the calls in their own way.

sssilviu
A: 

In PHP at least, they're basically just a way to set some restrictions on your objects to make Polymorphism more manageable - that is to say ensure different type of objects can all walk like a duck.

In other words - just a way to programatically ensure your objects have certain members and methods, and throw an error if they don't.

donatJ