The interface can be implemented by a class or a struct as shown in this example:
class MyClass: IMyInterface1
{
// class implementation
}
By this declaration the class MyClass is obligated to implement all members of the interface IMyInterface.
It is also possible for a class to implement more than one interface:
class MyClass: IMyInterface1, IMyInterface2
{
//class implementation
}
A class can also implement another class in addition to the interfaces:
class MyClass: MyBaseClass, IMyInterface1, IMyInterface2
{
//class implementation
}
In the following example, the class Point implements the interface the interface IPoint. Notice that all the fields are included in the class but none are included in the interface.
//Example 8-1.cs
//Interface example
using System;
interface IPoint
{
//Property signatures:
int Myx
{
get; set;
}
int Myy
{
get; set;
}
}
class Point: IPoint
{
//Fields:
private int x;
private int y;
//constructor:
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
//Property implementation:
public int Myx
{
get { return x; }
set { x = value; }
}
public int Myy
{
get { return y; }
set ( y = value; }
}
public static void DisplayMyPoint(IPoint myPoint)
{
Console.WriteLine(“({0},{1}”, myPoint.Myx, myPoint.Myy);
}
}
class MyClass
{
static void Main()
{
Point myPoint = new Point(12,300);
Console.Write(“My point is created at: “);
Point.DisplayMyPoint(myPoint);
}
}
Notes about the preceding example:
I. If we don’t implement all the members of the interface, we get a compilation error. Try commenting the properties (Myx and Myy) in the class to see the compiler error message.
II. Notice also that it is possible to pass a parameter of the type IPoint to the method DisplayMyPoint. We can, of course, pass a parameter of the type Point instead.
III. Notice also that it is possible to pass a parameter of the type IPoint to the method DisplayMyPoint. We can, of course, pass a parameter of the type Point instead.
Wednesday, March 24, 2010
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment