Re: Trying to understand the purpose of interfaces
- From: Bob Jones <robert@xxxxxxxxxxxxxx>
- Date: Sat, 04 Nov 2006 05:08:08 GMT
Lets say you have a bunch of ducks. You have your mallard, rubber duckie, etc. Now all these ducks to the same things, but they do them in different ways. Ducks quack, but mallard's quack is "quack!" and the rubber duckie's quack is "squeak!" They both swim, but slightly differently. More over, however, they're all ducks.
You want to implement ducks but C# is a strongly typed language. You can't write code to handle a mallard and a rubber duckie because they're different classes - unless you use interfaces.
So you define a "Iduck" interface and list the behaviors (methods) that all ducks have: swim, quack, fly, etc. Then, when you define each individual duck class, implementing the Iduck interface, with different implementations for swim, fly, etc. and then you can write code that handles "Iducks" and you can give it any old kind of duck - because they're all ducks (i.e. implementing the same interface) with the same general duck behaviors (methods).
Note that when a class implements an interface it is somewhat like inheritance. Please don't anyone start arguing the technical nits here; as a practical matter you can think in terms of "a mallard is an Iduck" and that works fine. The neat thing is that a class can implement any number of interfaces, while it can only inherit from one class. It's not unusual to see interfaces with no methods defined; it's only purpose being to handle anything as that general "type".
On 2006-11-03 16:56:17 -0600, "jm" <needin4mation@xxxxxxxxx> said:
I am having trouble understanding the purposes of an interface, even
though the concept of interfaces is around me all the time (user
interface, for example). I'm just not understanding software
interfaces.
Like anything else, it appears Interfaces are by design something that
requires documentation. I know this may be obvious, but if I have a
class A and I say, well, class A implements IMyInterface. The fact
that it implements IMyInterface is supposed to mean something to me. I
am guessing that MS and other Sun have a lot of well defined and
documented interfaces that I would eventually care about.
I guess I am looking for a time when their absence would require them.
I think that by seeing their missing from a given situation that
requires them (or would be hard without them), I might see and
understand their necessity and understand.
Does anyone have an example of this? I hope this made some sense.
Thank you.
.
- Follow-Ups:
- References:
- Prev by Date: Re: FTP Parsing directory listings
- Next by Date: Re: Memory Cleanup
- Previous by thread: RE: Trying to understand the purpose of interfaces
- Next by thread: Re: Trying to understand the purpose of interfaces
- Index(es):
Relevant Pages
|