Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Sobrecarga de Métodos | Métodos
Java Avanzado
course content

Contenido del Curso

Java Avanzado

Java Avanzado

1. Estructura Profunda de Java
2. Métodos
3. String Avanzado
4. Clases
5. Clases Avanzadas

book
Sobrecarga de Métodos

Uso de un método con diferentes parámetros

Java nos permite escribir diferentes métodos con el mismo nombre. Estos métodos pueden tener diferentes tipos de retorno y/o tipos de parámetros. Esto se hace para que podamos utilizar estos métodos con distintos tipos. Tomemos como ejemplo un método para imprimir un arreglo:

Podemos escribir este método para aceptar valores de tipo int, pero ¿qué sucede si necesitamos imprimir un arreglo de tipo char? ¿Debemos escribir un método con un nombre diferente?

Java proporciona la sobrecarga de métodos para este propósito.

Veamos un ejemplo de impresión de datos e inversión de un arreglo del capítulo anterior:

Main.java

Main.java

copy
123456789101112131415161718192021222324252627
// method to reverse an int array static int[] flipArray(int[] array) { // creating a new array to store the reversed elements int[] result = new int[array.length]; int index = 0; // iterating over the input array in reverse order for (int i = array.length - 1; i > 0; i--) { result[index] = array[i]; index++; } // returning the reversed int array return result; } // method to reverse a char array static char[] flipArray(char[] array) { // creating a new array to store the reversed elements char[] result = new char[array.length]; int index = 0; // iterating over the input array in reverse order for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } // returning the reversed char array return result; }

Sobrecargamos el método flipArray para aceptar y devolver diferentes parámetros: int y char. Si invocamos este método, puede aceptar y devolver tanto tipos int como char.

Ahora sobrecarguemos el método para mostrar un arreglo en pantalla. Este método también debe aceptar y devolver tipos int y char:

Main.java

Main.java

copy
12345678910111213141516171819
// method to print an int array static void printArrayToTheConsole(int[] array) { // iterating through each element of the int array for (int element : array) { System.out.print(element + " "); } // printing a blank line after the array System.out.println(); } // method to print a char array static void printArrayToTheConsole(char[] array) { // iterating through each element of the char array for (char element : array) { System.out.print(element + " "); } // printing a blank line after the array System.out.println(); }

Aquí hemos sobrecargado el método printArrayToTheConsole para aceptar y devolver valores de tipo int y char.

Ahora combinemos los métodos sobrecargados y utilicémoslos en el método main para un arreglo de tipo int y un arreglo de tipo char:

Main.java

Main.java

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
package com.example; public class Main { // main method to run the application public static void main(String[] args) { // do not modify the code below int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; char[] charArray = {'s', 'b', 'c', 'd', 'e', 'f', 'g'}; printArrayToTheConsole(flipArray(intArray)); printArrayToTheConsole(flipArray(charArray)); } // method to reverse an int array static int[] flipArray(int[] array) { int[] result = new int[array.length]; int index = 0; // iterating over the array in reverse order for (int i = array.length - 1; i > 0; i--) { result[index] = array[i]; index++; } return result; } // method to reverse a char array static char[] flipArray(char[] array) { char[] result = new char[array.length]; int index = 0; // iterating over the array in reverse order for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } return result; } // method to print an int array to the console static void printArrayToTheConsole(int[] array) { // printing each element of the int array for (int element : array) { System.out.print(element + " "); } System.out.println(); } // method to print a char array to the console static void printArrayToTheConsole(char[] array) { // printing each element of the char array for (char element : array) { System.out.print(element + " "); } System.out.println(); } }

Hemos sobrecargado dos métodos diferentes añadiendo la capacidad de utilizar estos métodos con arreglos de tipo char. También hemos cambiado ligeramente los nombres de estos métodos, ya que ahora podemos sobrecargarlos varias veces para aceptar y devolver valores de diferentes tipos.

Para verificar esto, creamos dos arreglos diferentes, uno de tipo int y otro de tipo char, y luego pasamos estos arreglos a los métodos sobrecargados, obteniendo los resultados correctos.

Por cierto, ya te has encontrado con métodos sobrecargados antes. Por ejemplo, el método String de substring() está sobrecargado y puede tener un parámetro, int beginIndex, o dos parámetros, int beginIndex, int endIndex. La sobrecarga de métodos es muy útil y se utiliza comúnmente en la práctica.

question mark

¿Cuántas veces podemos sobrecargar un método?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 6

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

course content

Contenido del Curso

Java Avanzado

Java Avanzado

1. Estructura Profunda de Java
2. Métodos
3. String Avanzado
4. Clases
5. Clases Avanzadas

book
Sobrecarga de Métodos

Uso de un método con diferentes parámetros

Java nos permite escribir diferentes métodos con el mismo nombre. Estos métodos pueden tener diferentes tipos de retorno y/o tipos de parámetros. Esto se hace para que podamos utilizar estos métodos con distintos tipos. Tomemos como ejemplo un método para imprimir un arreglo:

Podemos escribir este método para aceptar valores de tipo int, pero ¿qué sucede si necesitamos imprimir un arreglo de tipo char? ¿Debemos escribir un método con un nombre diferente?

Java proporciona la sobrecarga de métodos para este propósito.

Veamos un ejemplo de impresión de datos e inversión de un arreglo del capítulo anterior:

Main.java

Main.java

copy
123456789101112131415161718192021222324252627
// method to reverse an int array static int[] flipArray(int[] array) { // creating a new array to store the reversed elements int[] result = new int[array.length]; int index = 0; // iterating over the input array in reverse order for (int i = array.length - 1; i > 0; i--) { result[index] = array[i]; index++; } // returning the reversed int array return result; } // method to reverse a char array static char[] flipArray(char[] array) { // creating a new array to store the reversed elements char[] result = new char[array.length]; int index = 0; // iterating over the input array in reverse order for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } // returning the reversed char array return result; }

Sobrecargamos el método flipArray para aceptar y devolver diferentes parámetros: int y char. Si invocamos este método, puede aceptar y devolver tanto tipos int como char.

Ahora sobrecarguemos el método para mostrar un arreglo en pantalla. Este método también debe aceptar y devolver tipos int y char:

Main.java

Main.java

copy
12345678910111213141516171819
// method to print an int array static void printArrayToTheConsole(int[] array) { // iterating through each element of the int array for (int element : array) { System.out.print(element + " "); } // printing a blank line after the array System.out.println(); } // method to print a char array static void printArrayToTheConsole(char[] array) { // iterating through each element of the char array for (char element : array) { System.out.print(element + " "); } // printing a blank line after the array System.out.println(); }

Aquí hemos sobrecargado el método printArrayToTheConsole para aceptar y devolver valores de tipo int y char.

Ahora combinemos los métodos sobrecargados y utilicémoslos en el método main para un arreglo de tipo int y un arreglo de tipo char:

Main.java

Main.java

copy
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
package com.example; public class Main { // main method to run the application public static void main(String[] args) { // do not modify the code below int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; char[] charArray = {'s', 'b', 'c', 'd', 'e', 'f', 'g'}; printArrayToTheConsole(flipArray(intArray)); printArrayToTheConsole(flipArray(charArray)); } // method to reverse an int array static int[] flipArray(int[] array) { int[] result = new int[array.length]; int index = 0; // iterating over the array in reverse order for (int i = array.length - 1; i > 0; i--) { result[index] = array[i]; index++; } return result; } // method to reverse a char array static char[] flipArray(char[] array) { char[] result = new char[array.length]; int index = 0; // iterating over the array in reverse order for (int i = array.length - 1; i >= 0; i--) { result[index] = array[i]; index++; } return result; } // method to print an int array to the console static void printArrayToTheConsole(int[] array) { // printing each element of the int array for (int element : array) { System.out.print(element + " "); } System.out.println(); } // method to print a char array to the console static void printArrayToTheConsole(char[] array) { // printing each element of the char array for (char element : array) { System.out.print(element + " "); } System.out.println(); } }

Hemos sobrecargado dos métodos diferentes añadiendo la capacidad de utilizar estos métodos con arreglos de tipo char. También hemos cambiado ligeramente los nombres de estos métodos, ya que ahora podemos sobrecargarlos varias veces para aceptar y devolver valores de diferentes tipos.

Para verificar esto, creamos dos arreglos diferentes, uno de tipo int y otro de tipo char, y luego pasamos estos arreglos a los métodos sobrecargados, obteniendo los resultados correctos.

Por cierto, ya te has encontrado con métodos sobrecargados antes. Por ejemplo, el método String de substring() está sobrecargado y puede tener un parámetro, int beginIndex, o dos parámetros, int beginIndex, int endIndex. La sobrecarga de métodos es muy útil y se utiliza comúnmente en la práctica.

question mark

¿Cuántas veces podemos sobrecargar un método?

Select the correct answer

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 6
some-alt