Interfaces in Object-Oriented Programming

Welcome to another post about object-oriented programming.

Today we'll see what an interface is, which is directly related to inheritance, as we explained in the inheritance post, a class can inherit or implement as many interfaces as it needs.

 

1 - What is an interface in object-oriented programming

An interface is a contract between two entities, meaning that an interface provides a service to a consuming class. Therefore, the interface only shows us the declaration of its methods, not their implementation, thus allowing encapsulation.

Although this rule of using only the method signature in the interface may be affected in C#8, as we've already seen in the preview, since it will allow adding a body in interface declarations, but for now, this cannot be done.

An interface is defined using the reserved word "interface." And generally, we indicate in the name that it is an interface by starting its name with a capital I.

public interface IPieza
{  
}

Interfaces can contain the following members:

  • Methods
  • Properties
  • Indexers
  • Events
public interface IPieza
{
    decimal Area();
    decimal Perimetro();
}

As we see in the example, we've declared two methods.

 

 

2 - Implementing an interface

To implement an interface, we need to declare a class or a 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 can leave them throwing 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 we implement an interface, we need to ensure a few things:

  • The methods and their return types must match both in the interface and in the class.
  • The parameters must be the same.
  • Interface methods must be public.
  • Using interfaces improves code quality and application performance.

 

3 - Multiple classes inheriting from an interface

One of the most common cases in object-oriented programming is having several classes inherit from an interface, which means we must implement the code in both. For this, we create in the code the triangle (right triangle) class along with the previous square class, both are pieces. Therefore, 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, in both cases we have area and perimeter.

If we remember from inheritance, classes are also of the type they inherit from, which means that both Square and TrianguloRectangulo can be converted to 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 25
The perimeter of the square is 20
The area of the triangle is 7.5
The perimeter of the triangle is 13.8309518948453

This example is very simple, but imagine a list with over a million pieces, each with different shapes. Since they all inherit from IPieza, we can have a loop with just one line, a foreach loop that executes the Area() method if what we want is to display the area.

Using interfaces greatly facilitates programming when translating real-world entities into code.

Of course, you can have additional methods, usually private, inside the class, but they will not be accessible through the interface.

 

 

4 - Multiple interfaces in a single class

It may be the case that we need to implement more than one interface in our class; for this, there is no problem, we simply separate them with commas.

But those interfaces may contain a method with the same name, same return value, and the same parameters.

The way to differentiate one from the other is in the 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 we can see, we don't use an access modifier in the method implementation.

This post was translated from Spanish. You can see the original one here.
If there is any problem you can add a comment bellow or contact me in the website's contact form

Uso del bloqueador de anuncios adblock

Hola!

Primero de todo bienvenido a la web de NetMentor donde podrás aprender programación en C# y .NET desde un nivel de principiante hasta más avanzado.


Yo entiendo que utilices un bloqueador de anuncios como AdBlock, Ublock o el propio navegador Brave. Pero te tengo que pedir por favor que desactives el bloqueador para esta web.


Intento personalmente no poner mucha publicidad, la justa para pagar el servidor y por supuesto que no sea intrusiva; Si pese a ello piensas que es intrusiva siempre me puedes escribir por privado o por Twitter a @NetMentorTW.


Si ya lo has desactivado, por favor recarga la página.


Un saludo y muchas gracias por tu colaboración

© copyright 2025 NetMentor | Todos los derechos reservados | RSS Feed

Buy me a coffee Invitame a un café