Object-Oriented Programming and Classes

In this tutorial, we will see how to bring reality into our applications by using object-oriented programming, also known as OOP.

 

1 - What is object-oriented programming?

It is a paradigm that turns real world objects into code entities called classes. This may seem very complex, but it is not at all.

Let’s imagine a real-world object, such as a motorcycle.

imagen moto

As we can see in the image, we have two entities: Piloto and Moto.

Depending on the business logic, you must decide whether the motorcycle contains the rider, or the rider contains the motorcycle. For our example, the motorcycle will contain the rider.

When we convert the motorcycle into an object, we should think about its characteristics, such as brand, model, number of wheels, engine capacity, etc. These characteristics will become our properties.

In addition to that, motorcycles can perform actions, like starting, accelerating, braking, changing gear – all these actions will be represented as methods.

Therefore, a class is a specific type used to create objects.

As we remember from previous tutorials, we have primitive types like int, decimal, etc. Classes are just another type, but customized to our needs.

 

2 - Creating a class

To create a class you need to use the reserved word class followed by the name you want to use. Like in all code blocks, you use braces { and } to define where it starts and ends, and inside the block, you will declare your properties and methods.

class Moto
{
    public decimal VelocidadMaxima { get; set; }
    public int NumeroRuedas { get; set; }
    public Motorista Piloto { get; set; }

    public Acelerar(){
        //Código aquí
    }
    public Arrancar(){
        //Código aquí
    }
}

As we see, we also use the reserved word public, which is an access modifier, covered in the course about access modifiers.

 

2.1 - Creating an instance of a class

An object is the in-memory representation of a class, and you can create as many objects from a class as you want using the reserved word new.

Moto aprilia = new Moto();

After that, we can assign values to its properties and also call its methods. Since we have Piloto inside the Moto type, we can also assign values to it.

aprilia.VelocidadMaxima = 320;
aprilia.NumeroRuedas = 2;
aprilia.Acelerar();

aprilia.Piloto.Nacionalidad = "ESP";

 

 

3 - Constructors

As we have seen, when we create an instance of the class using new Moto(), what we are actually doing is calling the default constructor from System.Object. But what if we don't want to use the default constructor? The default constructor initializes all variables to null.

To solve this, we can create a custom constructor where we can assign values manually, as you can see in the example. Now, when we do Moto aprilia = new Moto();, by default it will have VelocidadMaxima of 320 and NumeroRuedas of 2.

class Moto
{
    public decimal VelocidadMaxima { get; set; }
    public int NumeroRuedas { get; set; }
    public Motorista Piloto { get; set; }
    public string Marca { get; set; }
    public string Modelo { get; set; }

    public Moto(){
        VelocidadMaxima = 320;
        NumeroRuedas = 2;
    }

    public Acelerar(){
        //Código aquí
    }
    public Arrancar(){
        //Código aquí
    }
}

But what happens if we have multiple motorcycles?

In our example, since the values are assigned in the default constructor, every motorcycle would be created with these same values. This means that, in the following statements:

Moto aprilia = new Moto();
Moto Ducati = new Moto();

Both motorcycles would have VelocidadMaxima of 320 and NumeroRuedas with a value of 2, so the values may not be correct for all cases.

To fix this, we add a constructor that accepts values as parameters. By using operator overloading we can create as many constructors as we need.

class Moto
{
    public decimal VelocidadMaxima { get; set; }
    public int NumeroRuedas { get; set; }
    public Motorista Piloto { get; set; }
    public string Marca { get; set; }
    public string Modelo { get; set; }

    public Moto(decimal velocidadMaxima, int NumeroRuedas){
        VelocidadMaxima = velocidadMaxima;
        NumeroRuedas = NumeroRuedas;
    }

    public Moto(string marca, string modelo){
        Marca = marca;
        modelo = modelo;
    }

    public Moto(){
        VelocidadMaxima = 320;
        NumeroRuedas = 2;
    }

    public Acelerar(){
        //Código aquí
    }
    public Arrancar(){
        //Código aquí
    }
}

As you can see, both constructors work perfectly.

Moto aprilia = new Moto("Aprilia", "RX");
Moto motoSinMarca = new Moto(210,2);

 

 

4 - Inheritance in programming

Another very important feature in object-oriented programming is inheritance. It allows us to inherit information from a parent class into its child.

In the previous motorcycle example, suppose we also have a car. Both are vehicles, so they will have features in common, like brand, model, number of wheels, and other differences, like engine capacity for motorcycles or drive type for cars. Using inheritance saves us many lines of code and reduces complexity in our programs.

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

    public Vehiculo(decimal velocidadMaxima, int NumeroRuedas){
        VelocidadMaxima = velocidadMaxima;
        NumeroRuedas = NumeroRuedas;
    }

    public Vehiculo(string marca, string modelo){
        Marca = marca;
        Modelo = modelo
    }

    public Acelerar(){
        //Código aquí
    }

    public Arrancar(){
        //Código aquí
    }
}

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

    public Moto(decimal velocidadMaxima, int NumeroRuedas, int cilindrada) : base(velocidadMaxima, NumeroRuedas){
       Cilindrada = cilindrada;
    }

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

   public void HacerCaballito(){
       //codigo
   }
}

class Coche : Vehiculo 
{
    public string Traccion { get; set; }

    public Coche(string marca, string modelo, string Traccion) : base(marca, modelo){

    }

    public bool CerrarPuertas(){
        
    }

}

As you can see, both Coche and Moto inherit from Vehiculo using :. This means both classes can access the methods and properties of Vehiculo, in addition to their own.

Another interesting detail is that, as we can see in the constructor, the child class calls the constructor of the parent class using the reserved word : Base() and passing the parameters that constructor needs.

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é