Introduction to Interfaces
Introduction to Interfaces
Introduction
An interface is a structural layout that resembles a class but has the following characteristics:
Practical Learning: Introducing Interfaces
Creating an Interface
The basic formula to create an interface is:
[ access-modifier(s) ] interface name { members }
The access modifiers can be any of those we have seen in previous lessons (public, protected, internal, private, or protected internal). If you omit the access modifier, it is assumed to be public. To create an interface, you use the interface. This keyword is followed by the name of the interface. By tradition, the name of an interface starts with I. The section between the curly brackets is the body of the interface.
To create an interface, you can use a text editor such as Notepad, include your code, and save the file with .cs extension. If you are using Microsoft Visual Studio, to created an interface, on the main menu, click Project -> Add New Item... In the Add New Item dialog box, select Interface, give it a name and click Add.
Practical Learning: Creating an Interface
namespace Geometry20
{
public interface IPolygon
{
}
}
Implementing an Interface
After creating an interface, to implement it, as mentioned in our introduction, create a class or a structure that derives from the interface.
interface IPolygon
{
}
public class Triangle : IPolygon
{
}
As with other classes, once you have the class, you can create objects from it and instantiate it using the new operator.
Practical Learning: Implementing an Interface
namespace Geometry20
{
public class EquilateralTriangle : IPolygon
{
}
}
Interfaces and Objects
Creating an Object from an Interface-Derived Class
After implementing an interface, you can create an object of a class that implements it. Here is an example from the the above class:
private void btnCreate_Click(object sender, EventArgs e)
{
EquilateralTriangle et = new EquilateralTriangle();
}
By using the name of the class to declare a variable, you can access any non-private member of the class.
Declaring a Variable of Interface Type
As seen for an abstract class, you cannot declare a variable of an interface and use it directly as you would a regular class. Instead, you can declare a variable by using the name of the interface but not allocate memory for the variable. Here is an example:
private void btnCreate_Click(object sender, EventArgs e) { IPolygon figure; }
When allocating memory for the object using the new operator, you must use a class that implements that interface. Here is an example:
private void btnCreate_Click(object sender, EventArgs e)
{
IPolygon figure;
figure = new EquilateralTriangle();
}
You can also declare the variable and allocate its memory on the same line. Here is an example:
private void btnCreate_Click(object sender, EventArgs e)
{
IPolygon figure = new EquilateralTriangle();
}
After that, you can use the object.
Introduction to the Members of an Interface
As mentioned earlier, the purpose of an interface is to create a skeleton for classes and/or structures. When creating an interface, in its body, create the necessary members. Unlike classes and structures, the following keywords are not allowed on the members of an interface: private, public, protected, internal, static, abstract, virtual, or override.
In the class or a structure that is based on the interface, you must implement the members of the interface. This means that you must create a definition for each member of the interface.
Interfaces and Properties
A Property in an Interface
An interface can contain one or more properties. If the property is intended to be read-only, create it using the formula we saw for automatic read-only properties, that is, without a body. Here is an example:
interface IPolygon
{
double Area { get; }
}
When implementing the property, if it is a simple property that doesn't need to validate any value, you can simply apply the desired access level. Here is an example:
interface IPolygon { double Area { get; } } public class Triangle : IPolygon { public double Area { get; } }
Otherwise, you can create a body for the property.
In the same way, if the property is intended to be write-only, in the body of the interface, create it and then implement it in a deriving class.
If a property is intended to be read-write, create it without its body in the interface. When implementing the property in a class, if it is a simple property, create it as an automatic property. If the property must validate its value, you can first create a private field and use it in the clauses of the property.
Practical Learning: Adding a Property to an Interface
namespace Geometry20
{
public interface IPolygon
{
int Edges { get; }
double Side { get; set; }
int InternalAngle { get; }
double Perimeter { get; }
double Area { get; }
}
}
using static System.Math; namespace Geometry20 { public class EquilateralTriangle : IPolygon { public int Edges { get { return 3; } } public double Side { get; set; } public int InternalAngle { get { return 60; } } public double Perimeter { get { return Side * Edges; } } public double Area { get { return Side * Side * Sqrt(3.00) / 4.00; } } } }
Control | (Name) | Text | Other Properties |
PictureBox | Image: triangle2.png |
||
Label | Equilateral Triangle | Times New Roman, 24pt, style=Bold | |
Label | ___________________ | ||
Label | Side: | ||
TextBox | txtSide | TextAlign: Right | |
Button | btnCalculate | Calculate | |
Label | ___________________ | ||
Label | Number of Edges: | ||
TextBox | txtEdges | TextAlign: Right | |
Label | Internal Angle: | ||
TextBox | txtInternalAngle | TextAlign: Right | |
Label | Degrees: | ||
Label | Perimeter: | ||
TextBox | txtPerimeter | TextAlign: Right | |
Label | Area: | ||
TextBox | txtArea | TextAlign: Right |
using System;
using System.Windows.Forms;
namespace Geometry20
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
double measure = 0.00;
try
{
measure = Convert.ToDouble(txtSide.Text);
}
catch (FormatException)
{
MessageBox.Show("Enter the value of the side.", "Geometry - Equilateral Triangle");
}
EquilateralTriangle et = new EquilateralTriangle();
et.Side = measure;
txtEdges.Text = et.Edges.ToString();
txtInternalAngle.Text = et.InternalAngle.ToString();
txtPerimeter.Text = et.Perimeter.ToString();
txtArea.Text = et.Area.ToString();
}
}
}
A Property of an Interface Type
Imagine you create an interface as we did above. Here is an example:
using System.Drawing; public interface IVehicle { int NumberOfTires { get; set; } int NumberOfDoors { get; set; } Color MainColor { get; set; } }
You can create one or more classes that implement such an interface. Here are examples:
using System.Drawing; public class Sedan : IVehicle { public int NumberOfTires { get; set; } public int NumberOfDoors { get; set; } public int NumberOfSeats { get; set; } public Color MainColor { get; set; } public string Make { get; set; } public string Model { get; set; } public int Year { get; set; } }
A property of a class can be of the type of an interface. You primarily create the property like one that is based on a class. Here is an example:
using System;
public class RentalOrder
{
// Rental Order #
public int InvoiceNumber { get; set; }
// The employee/clerk who processes/processed the rental order
public string EmployeeeNumber { get; set; }
// The vehicle that was rented
public IVehicle Car { get; set; }
public DateTime RentStartDate { get; set; }
public DateTime RentEndDate { get; set; }
}
When it comes time to use an interface-type property, you may have to indicate where the values of the property come from. In fact, at one time, you may have to initialize the property. In order to do this, you should/can (must) use a class that implements the interface. Here are examples:
private void btnOrderProcessing_Click(object sender, EventArgs e)
{
RentalOrder ro = new RentalOrder();
ro.InvoiceNumber = 100001;
ro.EmployeeeNumber = "309-247";
ro.RentStartDate = new DateTime(2018, 8, 12);
ro.RentEndDate = new DateTime(2018, 8, 17);
ro.Car = new Sedan();
}
From the interface-based property, you can access only the members of the interface. As a result, the following code would produce an error because you are trying to access a member of the class but that member is not part of the interface:
private void btnOrderProcessing_Click(object sender, EventArgs e)
{
RentalOrder ro = new RentalOrder();
ro.InvoiceNumber = 100001;
ro.EmployeeeNumber = "309-247";
ro.RentStartDate = new DateTime(2018, 8, 12);
ro.RentEndDate = new DateTime(2018, 8, 17);
ro.Car = new Sedan();
ro.Car.Make = "Ford";
}
Therefore, as mentioned already, remember that you can access only the members of the interface. Here are examples:
private void btnOrderProcessing_Click(object sender, EventArgs e)
{
RentalOrder ro = new RentalOrder();
ro.InvoiceNumber = 100001;
ro.EmployeeeNumber = "309-247";
ro.RentStartDate = new DateTime(2018, 8, 12);
ro.RentEndDate = new DateTime(2018, 8, 17);
ro.Car.NumberOfTires = 4;
ro.Car.NumberOfDoors = 4;
ro.Car.NumberOfSeats = 5;
ro.Car.MainColor = Color.Silver;
}
Interfaces and Methods/Functions
A Method in an Interface
An interface can contain one or more methods. A method is created like an abstract method in an abstract class. That is, a method without a body. The formula to follow is:
return-type method-name();
Here is an example:
interface IPolygon
{
double CalculatePerimeter();
}
In the same way, you can add as many methods as you want. In every class or structure that implements the interface, you must define each of the interface's method.
Practical Learning: Adding a Method to an Interface
namespace Geometry20
{
interface IPolygon
{
int Edges { get; }
double Side { get; set; }
int InternalAngle { get; }
double Perimeter { get; }
double Area { get; }
double CalculateInscribedRadius();
double CalculateCircumscribedRradius();
}
}
using static System.Math;
namespace Geometry20
{
public class EquilateralTriangle : IPolygon
{
public int Edges
{
get
{
return 3;
}
}
public double Side { get; set; }
public int InternalAngle
{
get
{
return 60;
}
}
public double Perimeter
{
get
{
return Side * Edges;
}
}
public double Area
{
get
{
return Side * Side * Sqrt(3.00) / 4.00;
}
}
public double CalculateInscribedRadius()
{
return Side * Sqrt(3.00) / 6.00;
}
public double CalculateCircumscribedRradius()
{
return Side * Sqrt(3.00);
}
}
}
An interface cannot contain a constructor. Instead, you can create one or more constructors in a class that implements the interface. From a constructor, you can access any of the members of the interface.
Imagine you declare a variable using the name of an interface. Here is an example:
private void btnCalculate_Click(object sender, EventArgs e)
{
double measure = Convert.ToDouble(txtSide.Text);
IPolygon et = new Triangle(measure);
}
If you declare a variable using an interface, you can access only the members of the interface. The non-interface members of the class would not be available. As a result, the following code would produce an error:
private void btnCalculate_Click(object sender, EventArgs e) { double measure = Convert.ToDouble(txtSide.Text); IPolygon et = new Triangle(measure); txtEdges.Text = et.Edges.ToString(); txtInternalAngle.Text = et.InternalAngle.ToString(); txtInscribedRadius.Text = et.CalculateInscribedRadius().ToString(); txtCircumscribedRadius.Text = et.CalculateCircumscribedRradius().ToString(); txtPerimeter.Text = et.Perimeter.ToString(); txtHeight.Text = et.Height.ToString(); txtArea.Text = et.Area.ToString(); }
Practical Learning: Using a Class that Implements an Interface
using static System.Math; namespace Geometry20 { public class EquilateralTriangle : IPolygon { public EquilateralTriangle(double edge) { Side = edge; } public int Edges { get { return 3; } } public double Side { get; set; } public int InternalAngle { get { return 60; } } public double Perimeter { get { return Side * Edges; } } public double Area { get { return Side * Side * Math.Sqrt(3.00) / 4.00; } } public double Height { get { return Side * Math.Sqrt(3.00) / 2.00; } } public double CalculateInscribedRadius() { return Side * Math.Sqrt(3.00) / 6.00; } public double CalculateCircumscribedRradius() { return Side * Math.Sqrt(3.00); } } }
Control | (Name) | Text | Other Properties |
Label | Inscribed Radius: | ||
TextBox | txtInscribedRadius | TextAlign: Right | |
Label | Circumscribed Radius: | ||
TextBox | txtCircumscribedRadius | TextAlign: Right | |
Label | Height: | ||
TextBox | txtHeight | TextAlign: Right |
using System; using System.Windows.Forms; namespace Geometry20 { public partial class Geometry : Form { public Geometry() { InitializeComponent(); } private void btnCalculate_Click(object sender, EventArgs e) { double measure = Convert.ToDouble(txtSide.Text); EquilateralTriangle et = new EquilateralTriangle(measure); txtEdges.Text = et.Edges.ToString(); txtInternalAngle.Text = et.InternalAngle.ToString(); txtInscribedRadius.Text = et.CalculateInscribedRadius().ToString(); txtCircumscribedRadius.Text = et.CalculateCircumscribedRradius().ToString(); txtPerimeter.Text = et.Perimeter.ToString(); txtHeight.Text = et.Height.ToString(); txtArea.Text = et.Area.ToString(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } } }
using static System.Math; namespace Geometry20 { public class EquilateralTriangle : IPolygon { public EquilateralTriangle(double edge) => Side = edge; public int Edges { get => 3; } public double Side { get; set; } public int InternalAngle { get => 60; } public double Perimeter { get => Side * Edges; } public double Area => Side * Side * Sqrt(3.00) / 4.00; public double Height => Side * Sqrt(3.00) / 2.00; public double CalculateInscribedRadius() => Side * Sqrt(3.00) / 6.00; public double CalculateCircumscribedRradius() => Side * Sqrt(3.00); } }
namespace Geometry21 { interface IPolygon { int Edges { get; } double Side { get; set; } int InternalAngle { get; } double Perimeter { get; } double Area { get; } double CalculateInscribedRadius(); double CalculateCircumscribedRradius(); } }
using System; namespace Geometry21 { public class Pentagon : IPolygon { public Pentagon(double edge) { Side = edge; } public int Edges { get { return 5; } } public double Side { get; set; } public int InternalAngle { get { return 108; } } public double Height { get { // http://mathworld.wolfram.com/Pentagon.html return Side * Math.Sqrt(5.00 + (2.00 * Math.Sqrt(5.00))) / 2.00; } } public double Perimeter { get { return Side * Edges; } } public double Area { get { return Side * Side * Math.Sqrt(5.00 * (5.00 + (2.00 * Math.Sqrt(5.00)))) / 4.00; } } public double CalculateInscribedRadius() { // http://mathworld.wolfram.com/Pentagon.html return Side * Math.Sqrt(25.00 + (10.00 * Math.Sqrt(5.00))) / 10.00; // https://en.wikipedia.org/wiki/Pentagon // return Side / (2.00 * Math.Sqrt(5.00 - Math.Sqrt(20.00))); } public double CalculateCircumscribedRradius() { // http://mathworld.wolfram.com/Pentagon.html return Side * Math.Sqrt(50.00 + (10.00 * Math.Sqrt(5.00))) / 10.00; } } }
Control | (Name) | Text | Other Properties |
PictureBox | Image: pentagon.png |
||
Label | Geometry - Pentagon | Times New Roman, 24pt, style=Bold | |
Label | ___________________ | ||
Label | Side: | ||
TextBox | txtSide | TextAlign: Right | |
Button | btnCalculate | Calculate | |
Label | ___________________ | ||
Label | Number of Edges: | ||
TextBox | txtEdges | TextAlign: Right | |
Label | Internal Angle: | ||
TextBox | txtInternalAngle | TextAlign: Right | |
Label | Degrees: | ||
Label | Inscribed Radius: | ||
TextBox | txtInscribedRadius | TextAlign: Right | |
Label | Circumscribed Radius: | ||
TextBox | txtCircumscribedRadius | TextAlign: Right | |
Label | Perimeter: | ||
TextBox | txtPerimeter | TextAlign: Right | |
Label | Area: | ||
TextBox | txtArea | TextAlign: Right |
Passing an Interface As Argument
A parameter of a method can be an interface type. In the body of such a method, you can access (only) the members of the interface. When calling the method, pass an object of the interface but that object should have been initialized with a class that implements the interface.
Practical Learning: Declaring a Variable of Interface Type
using System; using System.Windows.Forms; namespace Geometry21 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } void Display(IPolygon poly) { txtEdges.Text = poly.Edges.ToString(); txtInternalAngle.Text = poly.InternalAngle.ToString(); txtInscribedRadius.Text = poly.CalculateInscribedRadius().ToString(); txtCircumscribedRadius.Text = poly.CalculateCircumscribedRradius().ToString(); txtPerimeter.Text = poly.Perimeter.ToString(); txtArea.Text = poly.Area.ToString(); } private void btnCalculate_Click(object sender, EventArgs e) { try { double measure = Convert.ToDouble(txtSide.Text); IPolygon shape = new Pentagon(measure); Display(shape); } catch (FormatException) { MessageBox.Show("Make sure you provide a valid value for the side of the shape.", "Geometry - Polygon - Pentagon"); } } } }
Returning an Interface
A method can return an object of an interface type. When creating the method, specify its return type as the desired interface. In the body of the method, remember that you cannot simply instantiate an interface and directly use it as you would an object of a class. As a result, you cannot directly return an object of an interface type. Instead, you can declare a variable of the desired interface, initialize it with a class that implements the interface and then return that variable.
Practical Learning: Returning an Interface
using System; using System.Windows.Forms; namespace Geometry21 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Display(IPolygon poly) { txtEdges.Text = poly.Edges.ToString(); txtInternalAngle.Text = poly.InternalAngle.ToString(); txtInscribedRadius.Text = poly.CalculateInscribedRadius().ToString(); txtCircumscribedRadius.Text = poly.CalculateCircumscribedRradius().ToString(); txtPerimeter.Text = poly.Perimeter.ToString(); txtArea.Text = poly.Area.ToString(); } IPolygon Create() { double measure = 0.00; try { measure = Convert.ToDouble(txtSide.Text); } catch (FormatException) { MessageBox.Show("Make sure you provide a valid value for the side of the shape.", "Geometry - Polygon - Pentagon"); } IPolygon shape = new Pentagon(measure); return shape; } private void btnCalculate_Click(object sender, EventArgs e) { IPolygon shape = Create(); Display(shape); } } }
Interfaces and Inheritance
Inheriting an Interface
An interface can be derived from another interface (but an interface cannot derive from a class). Obviously the derived interface is supposed to add some behavior using methods and/or properties. Here is an example:
interface IPolygon
{
double Side { get; set; }
double Area { get; set; }
}
interface IPolyhedron : IPolygon
{
double Volume { get; set; }
}
As you should know already that nothing is implemented in an interface, a member of the parent interface cannot be defined in a derived interface. Also, any class that needs the behavior(s) of the derived interface must implement all members of the derived interface and those of the parent interface(s). Here is an example:
interface IPolygon
{
double Side { get; set; }
double Area { get; set; }
}
interface IPolyhedron : IPolygon
{
double Volume { get; set; }
}
public class Tetrahedron : IPolyhedron
{
public double Side { get; set; }
public double Area { get; set; }
public double Volume { get; set; }
}
In the same way, an interface can inherit from an interface that itself inherits from another interface, and from another, and so on.
Implementing Many Interfaces
In a C# program, you cannot create a class that inherits from many classes at the same time. Instead, you can create a class that implements more than one interface. To create a class based on more than one interface, after the colon applied to the class, enter the name of each interface and separate them with commas. Here is an example:
interface IPolygon
{
int Edges { get; }
double Side { get; set; }
double Perimeter { get; }
double Area { get; }
}
interface IColorizer
{
Color BorderColor { get; set; }
Color BackgroundColor { get; set; }
}
public class Triangle : IPolygon, IColorizer
{
public int Edges { get; }
public double Side { get; set; }
public double Perimeter { get; }
public double Area { get; }
public Color BorderColor { get; set; }
public Color BackgroundColor { get; set; }
}
In the above example, we created a class that implements only two interfaces. You can create a class that implements as many interfaces as you want. Also, the same interface can be implemented differently in different classes.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2003-2021, FunctionX | Next |
|