PDA

Click to See Complete Forum and Search --> : Interfaces...why? Please explain


visualsander
Mar 21st, 2002, 06:55 AM
Hi group

I'm currently buzzy trying to understand interfaces and why I should use them.

I've come across an example explaining interfaces but I don't see why I need the interface.

Here's the example in short:
I have an interface named:IncreaseSalary
I have 3 classes:
CSupervisor
CStaff
CManager

They all implement the same interface (IncreaseSalary) however the result of IncreaseSalary is different for all 3 classes, that is:
CSupervisor.IncreaseSalary raises the salary with 5 %
CStaff.IncreaseSalary raises the salary with 3 %
CManager.IncreaseSalary raises the salary with 2 %

This is code for the client:
Dim emp as IEmployee

Select Case UserInput
case "Manager"
Set emp = New Cmanager
case "Supervisor"
Set emp = New CSupervisor
case "Staff"
Set emp = New CStaff
End Select

'pay the employee
emp.IncreaseSalary

So far it's clear. What I don't get is why I need to use the interface. Can't I just create the Method's in the 3 classes? That way i do not need the interface?!?! What am I missing?

Please help me out.

Regards,

Sander

jim mcnamara
Mar 21st, 2002, 02:43 PM
Think of an interface as a common contract. No matter who enlists the help of the interface, they know how to use it.

In terms of someone who doesn't understand COM really well, this means that there are a fixed list of function pointers to a fixed array of functions, each with fixed parameters, returning fixed reults. Everything is known beforehand.

Fixed = unchanging

The advantage of an interface is that it's the same for everybody.
Do you know how to power on your PC? Could you come over here and power on my PC -- Even if it's a brand you haven't seen?

Yes.

Why? The interface to power on/power off is a switch. You know the rules for switches. The presence of a switch and rules for switch use makes up the interface. Therefore you can do it.

Same deal with any COM client. It desn't know anything about the server (you don't know whether I have 256MB of RAM for instance, and it doesn't matter), but it does know how to get the server to do something. It uses the interface. It knows what to expect, what to ask, how to ask it, and what kind of answer it will get back.