Welcome to another post about object-oriented programming.
Today we will discuss what an interface is, which is directly related to inheritance. As we explained in the post about inheritance, a class can inherit from or implement as many interfaces as needed.
Table of Contents
1 - What is an interface in object-oriented programming
An interface is a contract between two entities. This means that an interface provides a service to a consuming class. Therefore, the interface only shows us the declaration of its methods, not their implementation, allowing encapsulation.
Although the rule of using only method headers in the interface can change in C#8, as we saw in the update, since it will allow adding a body in interface declarations. However, for now, this is not possible.
An interface is defined using the reserved keyword "interface." Usually, we indicate an interface in the name by starting it with a capital "I."
public interface IPieza{ }
Interfaces may contain the following members:
- Methods
- Properties
- Indexers
- Events
public interface IPieza{ decimal Area(); decimal Perimetro();}
As seen in the example, we have declared two methods.
2 - Implementing an interface
To implement an interface, we need to declare a class or struct that inherits from the interface, and then implement all its members.
For example, we create the Square class and inherit from an interface, so we must implement its methods. By default, we could leave them as NotImplementedException().
public class Cuadrado : IPieza{ public decimal Lado { get; private set; } public Cuadrado(decimal lado) { Lado = lado; } public decimal Area() { return Lado * Lado; } public decimal Perimetro() { return Lado * 4; }}
When implementing an interface, we must ensure a couple of things:
- The methods and their return types must match in both the interface and the class.
- The parameters must be the same.
- Interface methods must be public.
- Using interfaces improves code and application performance.
3 - Multiple classes inheriting from an interface
One of the most common cases in object-oriented programming is when we have several classes inheriting from an interface, meaning both must implement the code. For this, we create the RightTriangle class alongside the previous Square class. Both are pieces, so both inherit from IPieza.
public class TrianguloRectangulo : IPieza{ public decimal LadoA { get; set; } public decimal LadoB { get; set; } public decimal Hipotenusa { get; set; } public TrianguloRectangulo(decimal ladoa, decimal ladob) { LadoA = ladoa; LadoB = ladob; Hipotenusa = CalculateHipotenusa(ladoa, ladob); } private decimal CalculateHipotenusa(decimal ladoa, decimal ladob) { return Convert.ToDecimal(Math.Sqrt((double)(ladoa * ladoa + ladob * ladob))); } public decimal Area() { return LadoA * LadoB / 2; } public decimal Perimetro() { return LadoA + LadoB + Hipotenusa; }}
As we can see, both have area and perimeter.
If you recall from inheritance, classes are also of the type from which they inherit, which means that both classes, Square and RightTriangle, can be cast as IPieza:
IPieza cuadrado = new Cuadrado(5);IPieza trianguloRectangulo = new TrianguloRectangulo(5, 3);Console.WriteLine($"The area of the square is {cuadrado.Area()}");Console.WriteLine($"The perimeter of the square is {cuadrado.Perimetro()}");Console.WriteLine($"The area of the triangle is {trianguloRectangulo.Area()}");Console.WriteLine($"The perimeter of the triangle is {trianguloRectangulo.Perimetro()}");//Result:The area of the square is 25The perimeter of the square is 20The area of the triangle is 7.5The perimeter of the triangle is 13.8309518948453
This example is very simple, but imagine a list with more than a million pieces, each with a different shape. Since they all inherit from IPieza, we can have a loop with a single line, a foreach loop that executes the Area() method if we want to display the area.
Using interfaces greatly facilitates programming when transferring real-world entities to code.
Of course, you can have additional methods, usually private, within the class, but these will not be accessible through the interface.
4 - Multiple interfaces in a single class
You might need to implement more than one interface in a class. There is no problem; just separate them with commas.
But those interfaces may contain a method with the same name, return type, and parameters.
The way we differentiate them is by their implementation inside the class.
public interface interfaz1{ void MetodoRepetido();}public interface interfaz2{ void MetodoRepetido();}public class EjemploRepeticionMetodo : interfaz1, interfaz2{ public EjemploRepeticionMetodo() { } void interfaz1.MetodoRepetido() { throw new NotImplementedException(); } void interfaz2.MetodoRepetido() { throw new NotImplementedException(); }}
As you can see, we do not use an access modifier in the method implementation.
If there is any problem you can add a comment bellow or contact me in the website's contact form