80 likes | 230 Views
Interfaces. Generic lists (and other generic classes) accept objects of the same type. This includes objects of classes which inherit from the list’s defined class. For example, you could have a Student class, and a BandMember class that inherits from it.
E N D
Interfaces • Generic lists (and other generic classes) accept objects of the same type. • This includes objects of classes which inherit from the list’s defined class. • For example, you could have a Student class, and a BandMember class that inherits from it. • Since by inheritance BandMember objects will have all of the properties and procedures of Student objects (and some more), they can be added to generic Student collections. • A BandMember object IS A Student object.
Interfaces • Sometimes, however, you will want to treat objects of very different types the same way. • For example, there is no logical inheritance structure between butterflies, eagles, and Airbus 300’s. • But they can all fly. So you decide on some basic flying procedures (takeoff, flylevel, land) and properties (altitude, airspeed). • You then make sure that your Butterfly, Eagle, and Airbus300 classes all implement these procedures and properties. • In this way, you can add objects of all three classes to a FlyingThings collection, and tell each object (in a loop, say) to takeoff, flylevel at 1000 feet, and land. • This coordination of similar properties and procedures across very different classes is called defining an interface.
Interface Example • Here’s what a flying thing interface looks like: • Note that it just provides the framework for the properties and subs: the names, parameters, and data types. Each class that implements these items can do so in its own way.
Implementing an Interface • Once you have defined an interface, VB makes it very easy to create classes which implement it. • Suppose I create a new class called “Eagle”. • To do this, I go to the Project menu, select Add Class, and name the Class Eagle. • VB creates this code: • I then type in “Implements IFlyingThing” • and when I hit Enter…
Voila! • VB has created the whole class for me!
Well, not entirely • I still have to teach my Eagles to takeoff, fly level, and land, but I have the entire framework needed for this class to implement IFlyingThing. • Why is this important? • I can add eagles, butterflies, Airbus300’s, and objects of any other class that implements the IFlyingThing interface, to a Generic.List(of IFlyingThing). • I can then tell any or all of them to Takeoff, FlyLevel, or Land, and know that they know how to do that (even though they’ll do them in different ways).
Interface Example For assignment 3, I have defined an interface for you called Idrawable. The classes that you create as part of the assignment must implement this interface.