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
namespace Geometry13 { internal class EquilateralTriangle { } }
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 a keyword named 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 Geometry13
{
internal interface IPolygon
{
}
}
Implementing an Interface
After creating an interface, to implement it, as mentioned in our introduction, create a class that derives from the interface.
interface IPolygon
{
}
internal 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 Geometry13
{
internal 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:
void Create()
{
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:
void Create() { 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:
void Create()
{
IPolygon figure;
figure = new EquilateralTriangle();
}
You can also declare the variable and allocate its memory on the same line. Here is an example:
void Create()
{
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. When creating an interface, in its body, create the necessary members. Unlike classes, the following keywords are not allowed on the members of an interface: private, public, protected, internal, static, abstract, virtual, or override.
In the class 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; } } internal 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 Geometry13
{
internal interface IPolygon
{
int Edges { get; }
double Side { get; set; }
int InternalAngle { get; }
double Perimeter { get; }
double Area { get; }
}
}
using static System.Math; namespace Geometry13 { internal 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; } } } }
using static System.Console;
using Geometry13;
WriteLine("===================================================");
WriteLine("Enter the value to process the equilateral triangle");
double measure = 0.00;
try {
Write("Measure : ");
measure = double.Parse(ReadLine()!);
}
catch(FormatException fe){
WriteLine("The value for the side of the equilateral triangle is not valid. Please report the error as follows: " + fe.Message);
}
EquilateralTriangle et = new EquilateralTriangle();
et.Side = measure;
WriteLine("===================================================");
WriteLine("Geometry - Equilateral Triangle");
WriteLine("===================================================");
WriteLine("Side: {0}", et.Side);
WriteLine("---------------------------------------------------");
WriteLine("Edges: {0}", et.Edges);
WriteLine("Internal Angle: {0}", et.InternalAngle);
WriteLine("Perimeter: {0}", et.Perimeter);
WriteLine("Area: {0}", et.Area);
WriteLine("===================================================");
=================================================== Enter the value to process the equilateral triangle Measure : 336.97 =================================================== Geometry - Equilateral Triangle =================================================== Side: 336.97 --------------------------------------------------- Edges: 3 Internal Angle: 60 Perimeter: 1010.9100000000001 Area: 49168.06441407663 =================================================== Press any key to close this window . . .
A Property of an Interface Type
Imagine you create an interface as we did above. Here is an example:
using System.Drawing; internal interface IVehicle { int NumberOfTires { get; set; } int NumberOfDoors { get; set; } string Color { get; set; } }
You can create one or more classes that implement such an interface. Here is an example:
internal class Sedan : IVehicle { public int NumberOfTires { get; set; } public int NumberOfDoors { get; set; } public int NumberOfSeats { get; set; } public string Color { 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;
internal 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 string RentStartDate { get; set; }
public string 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. To do this, you should/can (must) use a class that implements the interface. Here are examples:
void OrderProcessing()
{
RentalOrder ro = new RentalOrder();
ro.InvoiceNumber = 100001;
ro.EmployeeeNumber = "309-247";
ro.RentStartDate = "08/02/2018";
ro.RentEndDate = "08/17/2018";
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:
void OrderProcessing()
{
RentalOrder ro = new RentalOrder();
ro.InvoiceNumber = 100001;
ro.EmployeeeNumber = "309-247";
ro.RentStartDate = "08/02/2018";
ro.RentEndDate = "08/17/2018";
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:
void OrderProcessing()
{
RentalOrder ro = new RentalOrder();
ro.InvoiceNumber = 100001;
ro.EmployeeeNumber = "309-247";
ro.RentStartDate = "08/02/2018";
ro.RentEndDate = "08/17/2018";
ro.Car.NumberOfTires = 4;
ro.Car.NumberOfDoors = 4;
ro.Car.NumberOfSeats = 5;
ro.Car.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 that implements the interface, you must define each of the interface's methods.
Practical Learning: Adding a Method to an Interface
namespace Geometry13
{
internal 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;
internal 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:
void Calculate()
{
Write(Side);
double measure = double.Parse(ReadLine()); .Text);
IPolygon et = new Triangle(measure);
}
Interfaces and Property Initializers
We have seen that you can create a class that doesn't have a constructor even if that class implements an interface. In an interface, you can create an init property. If you do that, any class that implements that interface must have at least one constructor and you must use that constructor to initialize the property.
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.
Practical Learning: Using a Class that Implements an Interface
namespace Geometry13
{
internal interface IPolygon
{
int Edges { get; }
double Side { get; init; }
int InternalAngle { get; }
double Perimeter { get; }
double Area { get; }
double CalculateInscribedRadius();
double CalculateCircumscribedRradius();
}
}
using static System.Math; namespace Geometry13 { internal class EquilateralTriangle : IPolygon { public EquilateralTriangle(double edge) { Side = edge; } public int Edges { get { return 3; } } public double Side { get; init; } 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 Height { get { return Side * Sqrt(3.00) / 2.00; } } public double CalculateInscribedRadius() { return Side * Sqrt(3.00) / 6.00; } public double CalculateCircumscribedRradius() { return Side * Sqrt(3.00); } } }
using static System.Console; using Geometry13; WriteLine("==================================================="); WriteLine("Enter the value to process the equilateral triangle"); double measure = 0.00; try { Write("Measure : "); measure = double.Parse(ReadLine()!); } catch(Exception ex) when (ex is FormatException fe){ WriteLine("The value for the side of the equilateral triangle is not valid. Please report the error as follows: " + fe.Message); } EquilateralTriangle et = new EquilateralTriangle(measure); WriteLine("==================================================="); WriteLine("Geometry - Equilateral Triangle"); WriteLine("==================================================="); WriteLine("Side: {0}", et.Side); WriteLine("---------------------------------------------------"); WriteLine("Edges: {0}", et.Edges); WriteLine("Internal Angle: {0}", et.InternalAngle); WriteLine("Inscribed Radius: {0}", et.CalculateInscribedRadius()); WriteLine("Circumscribed Radius: {0}", et.CalculateCircumscribedRradius()); WriteLine("Perimeter: {0}", et.Perimeter); WriteLine("Height: {0}", et.Height); WriteLine("Area: {0}", et.Area); WriteLine("===================================================");
=================================================== Enter the value to process the equilateral triangle Measure : 1273.86 =================================================== Geometry - Equilateral Triangle =================================================== Side: 1273.86 --------------------------------------------------- Edges: 3 Internal Angle: 60 Inscribed Radius: 367.7317069549483 Circumscribed Radius: 2206.39024172969 Perimeter: 3821.58 Height: 1103.195120864845 Area: 702658.0683324456 =================================================== Press any key to close this window . . .
using static System.Math; namespace Geometry13 { internal 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); } }
=================================================== Enter the value to process the equilateral triangle Measure : 863.79 =================================================== Geometry - Equilateral Triangle =================================================== Side: 863.79 --------------------------------------------------- Edges: 3 Internal Angle: 60 Inscribed Radius: 249.3546945116534 Circumscribed Radius: 1496.1281670699204 Perimeter: 2591.37 Height: 748.0640835349602 Area: 323085.1373583316 =================================================== Press any key to close this window . . .
namespace Geometry14.Models
{
internal 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 Geometry14.Models { internal class Pentagon : IPolygon { public Pentagon(double edge) => Side = edge; public int Edges { get => 5; } public double Side { get; init; } public int InternalAngle { get => 108; } // http://mathworld.wolfram.com/Pentagon.html public double Height { get => Side * Sqrt(5.00 + (2.00 * Sqrt(5.00))) / 2.00; } public double Perimeter { get => Side * Edges; } public double Area { get => Side * Side * Sqrt(5.00 * (5.00 + (2.00 * Sqrt(5.00)))) / 4.00; } public double CalculateInscribedRadius() { // http://mathworld.wolfram.com/Pentagon.html return Side * Sqrt(25.00 + (10.00 * Sqrt(5.00))) / 10.00; // https://en.wikipedia.org/wiki/Pentagon // return Side / (2.00 * Math.Sqrt(5.00 - Math.Sqrt(20.00))); } // http://mathworld.wolfram.com/Pentagon.html public double CalculateCircumscribedRradius() => Side * Sqrt(50.00 + (10.00 * Sqrt(5.00))) / 10.00; } }
using static System.Console; using Geometry14.Models; WriteLine("==================================================="); WriteLine("Enter the value to process the Pentagon"); double measure = 0.00; try { Write("Measure: "); measure = double.Parse(ReadLine()!); } catch(FormatException fe){ WriteLine("The value for the side of the pentagon is not valid. Please report the error as follows: " + fe.Message); } IPolygon shape = new Pentagon(measure);
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 static System.Console; using Geometry14.Models; void Display(IPolygon poly) { WriteLine("==================================================="); WriteLine("Geometry - Polygon - Pentagon"); WriteLine("==================================================="); WriteLine("Side: {0}", poly.Side); WriteLine("---------------------------------------------------"); WriteLine("Edges: {0}", poly.Edges); WriteLine("Internal Angle: {0}", poly.InternalAngle); WriteLine("Inscribed Radius: {0}", poly.CalculateInscribedRadius()); WriteLine("Circumscribed Radius: {0}", poly.CalculateCircumscribedRradius()); WriteLine("Perimeter: {0}", poly.Perimeter); WriteLine("Area: {0}", poly.Area); WriteLine("==================================================="); } WriteLine("==================================================="); WriteLine("Enter the value to process the Pentagon"); double measure = 0.00; try { Write("Measure: "); measure = double.Parse(ReadLine()!); } catch(FormatException fe){ WriteLine("The value for the side of the pentagon is not valid. Please report the error as follows: " + fe.Message); } IPolygon shape = new Pentagon(measure); Display(shape);
=================================================== Enter the value to process the Pentagon Measure : 316.77 =================================================== Geometry - Polygon - Pentagon =================================================== Side: 316.77 --------------------------------------------------- Edges: 5 Internal Angle: 108 Inscribed Radius: 217.99825047382683 Circumscribed Radius: 269.4606565616757 Perimeter: 1583.85 Area: 172638.26450648528 =================================================== Press any key to close this window . . .
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 static System.Console; using Geometry14.Models; void Display(IPolygon poly) { WriteLine("==================================================="); WriteLine("Geometry - Polygon - Pentagon"); WriteLine("==================================================="); WriteLine("Side: {0}", poly.Side); WriteLine("---------------------------------------------------"); WriteLine("Edges: {0}", poly.Edges); WriteLine("Internal Angle: {0}", poly.InternalAngle); WriteLine("Inscribed Radius: {0}", poly.CalculateInscribedRadius()); WriteLine("Circumscribed Radius: {0}", poly.CalculateCircumscribedRradius()); WriteLine("Perimeter: {0}", poly.Perimeter); WriteLine("Area: {0}", poly.Area); WriteLine("==================================================="); } IPolygon Create() { WriteLine("==================================================="); WriteLine("Enter the value to process the Pentagon"); double measure = 0.00; try { Write("Measure: "); measure = double.Parse(ReadLine()!); } catch(Exception ex) when (ex is FormatException fe){ WriteLine("The value for the side of the pentagon is not valid. Please report the error as follows: " + fe.Message); } IPolygon shape = new Pentagon(measure); return shape; } IPolygon shape = Create(); Display(shape);
=================================================== Enter the value to process the Pentagon Measure : 1479.83 =================================================== Geometry - Polygon - Pentagon =================================================== Side: 1479.83 --------------------------------------------------- Edges: 5 Internal Angle: 108 Inscribed Radius: 1018.4056286854284 Circumscribed Radius: 1258.8185857235992 Perimeter: 7399.15 Area: 3767668.003743893 =================================================== Press any key to close this window . . .
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; }
}
internal 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; }
}
internal 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-2024, FunctionX | Sunday 30 April 2023 | Next |
|