Menu
Coddy logo textTech

Sobrecarga de constructores

Parte de la sección Programación Orientada a Objetos del Journey de Java de Coddy — lección 8 de 87.

La sobrecarga de constructores significa tener múltiples constructores con diferentes listas de parámetros. Usa this() para llamar a un constructor desde otro.

Múltiples constructores

public class Book {
    private String title;
    private String author;
    private int pages;
    
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
        this.pages = 0;
    }
}

Encadenamiento de constructores con this()

public class Book {
    private String title;
    private String author;
    private int pages;
    
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    public Book(String title, String author) {
        this(title, author, 0);  // Llama al constructor de 3 parámetros
    }
    
    public Book() {
        this("Unknown", "Unknown");  // Llama al constructor de 2 parámetros
    }
}

Uso

Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert");
Book b3 = new Book();

this() debe ser la primera instrucción en el constructor. El encadenamiento evita duplicar la lógica de asignación entre constructores.

challenge icon

Desafío

Intermedio

Crea tres constructores sobrecargados para la clase Product utilizando el encadenamiento de constructores:

  • Constructor de 3 parámetros: name, price, stock
  • Constructor de 2 parámetros: name, price (stock por defecto es 0)
  • Constructor por defecto: sin parámetros (name = "Unknown", price = 0, stock = 0)

Usa this() para encadenar constructores y evitar la duplicación de código.

Hoja de referencia

La sobrecarga de constructores permite tener múltiples constructores con diferentes listas de parámetros en la misma clase.

Ejemplo de múltiples constructores:

public class Book {
    private String title;
    private String author;
    private int pages;
    
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
        this.pages = 0;
    }
}

El encadenamiento de constructores con this() llama a un constructor desde otro para evitar la duplicación de código:

public class Book {
    private String title;
    private String author;
    private int pages;
    
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
    
    public Book(String title, String author) {
        this(title, author, 0);  // Llama al constructor de 3 parámetros
    }
    
    public Book() {
        this("Unknown", "Unknown");  // Llama al constructor de 2 parámetros
    }
}

Uso:

Book b1 = new Book("1984", "Orwell", 328);
Book b2 = new Book("Dune", "Herbert");
Book b3 = new Book();

Importante: this() debe ser la primera sentencia en el constructor.

Pruébalo tú mismo

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        double price = Double.parseDouble(scanner.nextLine());
        int stock = Integer.parseInt(scanner.nextLine());
        
        Product product1 = new Product(name, price, stock);
        Product product2 = new Product("Keyboard", 79.99);
        Product product3 = new Product();
        
        System.out.println("Product 1: " + product1.getName() + " - $" + product1.getPrice() + " (Stock: " + product1.getStock() + ")");
        System.out.println("Product 2: " + product2.getName() + " - $" + product2.getPrice() + " (Stock: " + product2.getStock() + ")");
        System.out.println("Product 3: " + product3.getName() + " - $" + product3.getPrice() + " (Stock: " + product3.getStock() + ")");
    }
}
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