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
Try It
325
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson27 folder of the download.
Lesson Requirements
Start a new project. Create a
Vehicle class with the properties NumberOfPassengers,
MilesPerGallon, and NumberOfCupHolders. Give it a constructor to make it easy to ini-
tialize a new object’s properties. Override its
ToString method so it returns the object’s
property values separated by the escape sequence
.
Make an
IDomicile interface that defines the properties SquareFeet, NumberOfBedrooms, and
NumberOfBathrooms. Also make it define a ToString method that returns a string as usual.
Derive the
MotorHome class from Vehicle, making it implement IDomicile. Give it a con-
structor to make it easy to initialize a new object’s properties. Override its
ToString method
so it returns the object’s property values separated by the escape sequence
.
Create an instance of the
MotorHome class. Then use its ToString method to display its
properties in a textbox.
Hints
Don’t forget to make the
MotorHome class’s constructor invoke the base class’s constructor.
If you don’t remember how, see the section “Invoking Other Constructors” in Lesson 24.
Also save a little work by making the
MotorHome class’s ToString method call the Vehicle
class’s version.
Step-by-Step
Start a new project. Create a
Vehicle class with the properties NumberOfPassengers,
MilesPerGallon, and NumberOfCupHolders. Give it a constructor to make it easy to initial-
ize a new object’s properties. Override its
ToString method so it returns the object’s property
values separated by the escape sequence
.
1. Use code similar to the following:
class Vehicle
{
// Properties.
public int NumberOfPassengers { get; set; }
public double MilesPerGallon { get; set; }
public int NumberOfCupHolders { get; set; }
596906c27.indd 325 4/7/10 12:34:09 PM
326
LESSON 27 Using interfaces
// Initializing constructor.
public Vehicle(int numberOfPassengers, double milesPerGallon,
int numberOfCupHolders)
{
NumberOfPassengers = numberOfPassengers;
MilesPerGallon = milesPerGallon;
NumberOfCupHolders = numberOfCupHolders;
}
// Return the object’s properties.
public override string ToString()
{
return
“NumberOfPassengers: “ + NumberOfPassengers +
“ MilesPerGallon : “ + MilesPerGallon +
“ NumberOfCupHolders: “ + NumberOfCupHolders;
}
}
Make an
IDomicile interface that defines the properties SquareFeet, NumberOfBedrooms,
and
NumberOfBathrooms. Also make it define a ToString method that returns a string as
usual.
1. Use code similar to the following:
interface IDomicile
{
int SquareFeet { get; set; }
int NumberOfBedrooms { get; set; }
double NumberOfBathrooms { get; set; }
string ToString();
}
Derive the
MotorHome class from Vehicle, making it implement IDomicile. Give it a con-
structor to make it easy to initialize a new object’s properties. Override its
ToString method
so it returns the object’s property values separated by the escape sequence
.
1. Use code similar to the following:
class MotorHome : Vehicle, IDomicile
{
// IDomicile methods.
public int SquareFeet { get; set; }
public int NumberOfBedrooms { get; set; }
public double NumberOfBathrooms { get; set; }
// Initializing constructor.
public MotorHome(int numberOfPassengers, double milesPerGallon,
int numberOfCupHolders, int squareFeet,
int numberOfBedrooms, double numberOfBathrooms)
: base(numberOfPassengers, milesPerGallon,
numberOfCupHolders)
{
SquareFeet = squareFeet;
596906c27.indd 326 4/7/10 12:34:09 PM
Exercises
327
NumberOfBedrooms = numberOfBedrooms;
NumberOfBathrooms = numberOfBathrooms;
}
// Return the object’s properties.
public override string ToString()
{
return base.ToString() +
“ SquareFeet: “ + SquareFeet +
“ NumberOfBedrooms: “ + NumberOfBedrooms +
“ NumberOfBathrooms: “ + NumberOfBathrooms;
}
}
Create an instance of the
MotorHome class. Then use its ToString method to display its prop-
erties in a textbox.
1. The following code creates an instance of the MotorHome class and displays its proper-
ties in
resultTextBox:
private void Form1_Load(object sender, EventArgs e)
{
// Make a MotorHome.
MotorHome motorHome = new MotorHome(6, 8.25, 32, 150, 3, 0.5);
// Display its properties.
resultTextBox.Text = motorHome.ToString();
}
Please select Lesson 27 on the DVD to view the video that accompanies this lesson.
EXERCISES
1. Build a program that defines the IDrawable interface described earlier in this lesson. Make
the
DrawableCircle and DrawableRectangle classes implement the interface. Hints: Give
DrawableCircle an additional Radius property and give DrawableRectangle additional
Width and Height properties. Use code similar to the following to draw the circle centered
at the point (X, Y):
// Draw the circle centered at (X, Y).
public void Draw(Graphics gr)
{
gr.FillEllipse(Background, X - Radius, Y - Radius,
2 * Radius, 2 * Radius);
gr.DrawEllipse(Foreground, X - Radius, Y - Radius,
2 * Radius, 2 * Radius);
}
596906c27.indd 327 4/7/10 12:34:09 PM
328
LESSON 27 Using interfaces
Use code similar to the following to draw the rectangle with upper-left corner (X, Y):
// Draw the rectangle.
public void Draw(Graphics gr)
{
gr.FillRectangle(Background, X, Y, Width, Height);
gr.DrawRectangle(Foreground, X, Y, Width, Height);
}
(For bonus points, make a DrawableStar class that has a NumberOfPoints property and
draws a star with that number of points.)
2. An array’s Sort method can take as a parameter an object that implements the generic
IComparer interface. Because this interface is generic, you can tell it what kinds of objects the
class can compare. For example,
IComparer<Car> means the class can compare Car objects.
Build a
Car class with the properties Name, MaxSpeed, Horsepower, and Price. Override the
ToString method to display the object’s properties formatted with fixed column widths so
the values for different
Cars in a listbox will line up nicely as shown in Figure 27-5. (The
listbox uses the fixed-width font Courier New so all of the letters have the same width.)
FIGURE 275
Build a CarComparer class that implements IComparer<Car>. Give it the following
SortType enum:
// Different kinds of sorts.
public enum SortType
{
ByName,
ByMaxSpeed,
ByHorsepower,
ByPrice,
}
Next give CarComparer a Sort property that has type SortType.
Finally give the
CarComparer a Compare method to satisfy the IComparer<Car> interface.
Use a switch statement to make the function return a value that depends on the
Sort value.
For example, if
Sort is ByPrice, then compare the two Cars’ prices. Make the function sort
the
MaxSpeed, Horsepower, and Price values in decreasing order.
596906c27.indd 328 4/7/10 12:34:10 PM
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.252