Polymorphism in Object-Oriented Programming

Welcome to this new post where we will continue talking about the fundamental pillars of object-oriented programming: polymorphism.

 

1- What is polymorphism in object-oriented programming

Polymorphism refers to the mechanism that allows us to have a method in a parent class as we saw with inheritance (link) and override it in the child class.

This means that we will have the same method in both classes, but in the child class it will perform different actions. Therefore, polymorphism is also known as method overriding.

There are two forms of polymorphism

  1. At runtime, which has to do with interfaces (post available in a few weeks)
  2. The second, called static polymorphism, determines which method will be executed during compilation.

 

 

2 - Static polymorphism in C#

2.1 - Using the new keyword

To indicate that we want to override a method, we must use the new keyword before the method name in the child class. This creates a new version of the method, only for that class.

With this, we allow "the same method" to perform different actions when called.

class Vehiculo
{
    public decimal VelocidadMaxima { get; set; }
    public int NumeroRuedas { get; set; }
    public string Marca { get; set; }
    public string Modelo { get; set; }

    public Vehiculo(string marca, string modelo)
    {
        Marca = marca;
        Modelo = modelo;
    }
    public void Acelerar()
    {
        Console.WriteLine("Acelerar vehículo");
        //Pisar el acelerador
    }

}

class Moto : Vehiculo
{
    public int Cilindrada { get; set; }

    public Moto(string marca, string modelo, int cilindrada) : base(marca, modelo)
    {
        Cilindrada = cilindrada;
    }

    public new void Acelerar()
    {
        //Girar el puño
        Console.WriteLine("Acelerar Moto");
    }
}

As we can see, the Acelerar method in the Moto class contains the new keyword. This means that if we call Moto.Acelerar(), the new code will be executed. On the other hand, if we have another class, such as Vehiculo.Acelerar(), or Coche.Acelerar() if we use the examples from the previous post, the method from the Vehiculo class will be executed, since Coche does not have a method that overrides the parent class method.

 

2.2- Using the keywords virtual and override

In the workplace, using the approach with the new keyword is not very common, as it gives the impression that it is not being overridden and can be quite confusing.

To avoid this confusion, you can indicate in the parent method that it will be overridden by using the virtual keyword

public virtual void Acelerar()
{
    Console.WriteLine("Acelerar vehículo");
    //Pisar el acelerador
}

And in the child class method, you use the override keyword to show that it will override the parent method.

It is important to remember that you cannot use the override keyword if the parent method is not virtual.

public override void Acelerar()
{
    //Girar el puño
    Console.WriteLine("Acelerar Moto");
}

Here is the full example:

class Vehiculo
{
    public decimal VelocidadMaxima { get; set; }
    public int NumeroRuedas { get; set; }
    public string Marca { get; set; }
    public string Modelo { get; set; }

    public Vehiculo(string marca, string modelo)
    {
        Marca = marca;
        Modelo = modelo;
    }
    public virtual void Acelerar()
    {
        Console.WriteLine("Acelerar vehículo");
        //Pisar el acelerador
    }

}

class Moto : Vehiculo
{
    public int Cilindrada { get; set; }

    public Moto(string marca, string modelo, int cilindrada) : base(marca, modelo)
    {
        Cilindrada = cilindrada;
    }

    public override void Acelerar()
    {
        //Girar el puño
        Console.WriteLine("Acelerar Moto");
    }
}
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é