The only way you can be absolutely sure that something implements the start/movebackwards/etc methods is by implementing the interface. Sure you can look at every class and 'see' that they do, but you cannot (programatically) be sure of it.
As such, the above example would be impossible to do without the interface, since you would have to type cast each object to its derived class:
for (int i = 0; i < obj.Count; i++)
{
if(o is Car) {
((Car)obj[i]).Start();
((Car)obj[i]).MoveBackward();
} else if (o is Bike) {
((Bike)obj[i]).Start();
((Bike)obj[i]).MoveBackward();
}
}
As you can imagine, that would become unmaintainable -very fast- if you planned on implementing more than a few types. So essentially, the interface lets you programatically know that the object contains certain methods, so that you can use those methods without
having to know what the derived class actually is.
dsmith3d
Member
30 Points
6 Posts
Re: Advantages of using Interfaces
May 24, 2006 06:47 PM|LINK
As such, the above example would be impossible to do without the interface, since you would have to type cast each object to its derived class:
for (int i = 0; i < obj.Count; i++)
{
if(o is Car) {
((Car)obj[i]).Start();
((Car)obj[i]).MoveBackward();
} else if (o is Bike) {
((Bike)obj[i]).Start();
((Bike)obj[i]).MoveBackward();
}
}
As you can imagine, that would become unmaintainable -very fast- if you planned on implementing more than a few types. So essentially, the interface lets you programatically know that the object contains certain methods, so that you can use those methods without having to know what the derived class actually is.