Menu
Coddy logo textTech

Constructores

Parte de la sección Programación Orientada a Objetos del Journey de C# de Coddy — lección 7 de 70.

Un constructor es un método especial que se ejecuta cuando creas un objeto. Inicializa las propiedades y campos del objeto.

Constructor predeterminado sin parámetros

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    // Constructor predeterminado
    public Book()
    {
        Title = "Unknown";
        Author = "Unknown";
    }
}

Constructor parametrizado

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    // Constructor con parámetros
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
    }
}

Sobrecarga de constructores - múltiples constructores

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
    
    // Constructor con dos parámetros
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
        Pages = 0;
    }
    
    // Constructor con tres parámetros
    public Book(string title, string author, int pages)
    {
        Title = title;
        Author = author;
        Pages = pages;
    }
}

Encadenamiento de constructores con this

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
    
    // Main constructor
    public Book(string title, string author, int pages)
    {
        Title = title;
        Author = author;
        Pages = pages;
    }
    
    // Calls the main constructor with default pages
    public Book(string title, string author) : this(title, author, 0)
    {
    }
}

Creación de objetos con diferentes constructores

Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);

Los constructores tienen el mismo nombre que la clase y no tienen tipo de retorno. Se ejecutan automáticamente cuando utilizas la palabra clave new. Puedes tener múltiples constructores con diferentes parámetros (sobrecarga).

challenge icon

Desafío

Intermedio

Crea tres constructores para la clase Product usando sobrecarga y encadenamiento de constructores:

  • Un constructor con 3 parámetros: name, price y stock
  • Un constructor con 2 parámetros: name y price (stock por defecto es 0)
  • Un constructor por defecto sin parámetros (name = "Unknown", price = 0, stock = 0)

Usa el encadenamiento de constructores con this para evitar la duplicación de código.

Hoja de referencia

Un constructor es un método especial que se ejecuta cuando creas un objeto. Inicializa las propiedades del objeto.

Los constructores tienen el mismo nombre que la clase y no tienen tipo de retorno. Se ejecutan automáticamente cuando utilizas la palabra clave new.

Constructor predeterminado sin parámetros:

public class Book
{
    public string Title { get; set; }
    
    public Book()
    {
        Title = "Unknown";
    }
}

Constructor parametrizado:

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
    }
}

Sobrecarga de constructores - múltiples constructores con diferentes parámetros:

public class Book
{
    public string Title { get; set; }
    public int Pages { get; set; }
    
    public Book(string title)
    {
        Title = title;
        Pages = 0;
    }
    
    public Book(string title, int pages)
    {
        Title = title;
        Pages = pages;
    }
}

Encadenamiento de constructores con this para evitar la duplicación de código:

public class Book
{
    public string Title { get; set; }
    public int Pages { get; set; }
    
    public Book(string title, int pages)
    {
        Title = title;
        Pages = pages;
    }
    
    public Book(string title) : this(title, 0)
    {
    }
}

Creación de objetos con diferentes constructores:

Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);

Pruébalo tú mismo

using System;

class Program
{
    static void Main()
    {
        string name = Console.ReadLine();
        decimal price = decimal.Parse(Console.ReadLine());
        int stock = int.Parse(Console.ReadLine());
        
        Product product1 = new Product(name, price, stock);
        Product product2 = new Product();
        Product product3 = new Product("Keyboard", 79.99m);
        
        Console.WriteLine($"Product 1: {product1.Name} - ${product1.Price} (Stock: {product1.Stock})");
        Console.WriteLine($"Product 2: {product2.Name} - ${product2.Price} (Stock: {product2.Stock})");
        Console.WriteLine($"Product 3: {product3.Name} - ${product3.Price} (Stock: {product3.Stock})");
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Programación Orientada a Objetos