324
LESSON 27 Using interfaces
DEFINING INTERFACES
The preceding sections give examples that implement predefined interfaces. This section explains
how you can define your own.
Defining an interface is a lot like defining a class with two main differences:
First, you use the keyword
interface instead of class in the declaration.
Second, you don’t provide any code for the properties, methods, and events that you declare
in the interface.
The following code shows a simple
IDrawable interface. The code includes a using System.Graphics
directive at the top of the file to make working with
Brush, Pen, and Graphics objects easier.
interface IDrawable
{
int X { get; set; }
int Y { get; set; }
Brush Background { get; set; }
Pen Foreground { get; set; }
void Draw(Graphics gr);
}
A class that implements IDrawable must provide X, Y, Background, and Foreground properties, and
a
Draw method.
You cannot provide an accessibility modifier such as
private to the items defined by an interface.
They are always assumed to be public, and a class that implements the interface must declare these
items as
public.
The declarations for the properties look like they are providing a default implementation for them,
but they actually only define the required accessors. A class that implements
IDrawable must still
provide its own implementations, although that can use auto-implemented properties. For example,
the following code shows how the
DrawableCircle class implements its X property:
public int X { get; set; }
This example might work better with true inheritance instead of an interface.
If you make a
Drawable class that implements the X, Y, Background, and
Foreground properties, other classes such as DrawableCircle could inherit
them. In this example an interface makes sense only if the classes already
inherit from some other class so they cannot also inherit from
Drawable.
TRY IT
In this Try It, you build the Vehicle class and the IDomicile interface described earlier in this
lesson. You then make a
MotorHome class that inherits from the first and implements the second.
Finally, you create an instance of the derived class.
596906c27.indd 324 4/7/10 12:34:09 PM