-
Interfaces
It was suggested to me to use Interfaces on a project i'm working on because you are supposed to be able to Iterate through a interface regardless of the classes that use them. I'm a bit confused on exactely what that means. Does it mean that I could have 5 different classes using one interface and I would be able to Iterate through all the classes that are using that Interface?
-
suppose you have the interface IPhysicalObject, which implements the following members: (C#, you get the idea though)
Code:
public interface IPhysicalObject
{
double GetWeight();
string GetName();
Color GetColor();
};
and you then have the following classes implement it:
Code:
public class MyBox : IPhysicalObject
{
public double GetWeight() { return 15.00; } ;
public String GetName() { return "My Heavy Red Chest"; };
public Color GetColor() { return Color.Red; };
public void Lock() { /* .... */ };
public void Unlock() { /* .... */ };
};
public class MyFridge: IPhysicalObject
{
public double GetWeight() { return 100.00; } ;
public String GetName() { return "My Big Refrigerator"; };
public Color GetColor() { return Color.White; };
public bool IsFoodRotten() { /* .... */ };
};
public class MyShirt: IPhysicalObject
{
public double GetWeight() { return .5; } ;
public String GetName() { return "My Green Shirt"; };
public Color GetColor() { return Color.Green; };
public void TurnInsideOut() { /* .... */ };
};
now suppose you wanted to keep these three things in an array together, maybe for some weird game where you had objects in a room:
Code:
myShirt shirt = new myShirt();
myFridge fridge = new myFridge();
myBox box = new myBox();
ArrayList myRoom = new ArrayList();
myRoom.Add(shirt);
myRoom.Add(fridge);
myRoom.Add(box);
since all the objects in your array implement IPhysicalObject, you can do something like this:
Code:
foreach(IPhysicalObject myObj in myRoom)
{
Console.Write("This Object [" + myObj.Name + "]");
Console.WriteLine("is " + myObj.Color.ToString());
}
-
Thank you sunburnt..
Excellent example, just what I needed....
:D
-
is that the only real use interfaces have? For when you iterate through a collection of different object using the same one?
I never bother using interfaces to be honest as i never saw the point of them. Am beginning to from this example tho!
Nick
-
They also provide a set of rules that a class must follow that can be enforced. for example if you make your app have a plugin system. You would want to create an interface so that all plugins have a set functions and properties that they MUST write code for because those are what the main app will expect.