Contenu du cours
Java Étendu
Java Étendu
Surcharge de Méthode
Utiliser une méthode avec différents paramètres
Java nous permet d'écrire différentes méthodes avec le même nom. Ces méthodes peuvent avoir différents types de retour et/ou types de paramètres. Cela est fait pour que nous puissions utiliser ces méthodes avec différents types. Prenons l'exemple d'une méthode pour imprimer un tableau :
Nous pouvons écrire cette méthode pour accepter des valeurs de type int
, mais que faire si nous devons imprimer un tableau de type char
? Devons-nous écrire une méthode avec un nom différent ?
Java fournit la surcharge de méthode à cet effet.
Jetons un coup d'œil à un exemple d'impression de données et d'inversion d'un tableau du chapitre précédent :
Main
// 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; }
Nous avons surchargé la méthode flipArray
pour accepter et retourner différents paramètres : int
et char
. Si nous invoquons cette méthode, elle peut accepter et retourner à la fois les types int
et char
.
Maintenant, surchargeons la méthode pour afficher un tableau à l'écran. Cette méthode doit également accepter et retourner les types int
et char
:
Main
// 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(); }
Ici, nous avons surchargé la méthode printArrayToTheConsole
pour accepter et retourner des valeurs int
et char
.
Maintenant, combinons les méthodes surchargées et utilisons-les dans la méthode main
pour un tableau de type int
et un tableau de type char
:
Main
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(); } }
Nous avons surchargé deux méthodes différentes en ajoutant la possibilité d'utiliser ces méthodes avec des tableaux de type char
. Nous avons également légèrement modifié les noms de ces méthodes, car nous pouvons maintenant les surcharger plusieurs fois pour accepter et retourner des valeurs de types différents.
Pour vérifier cela, nous avons créé deux tableaux différents, l'un de type int
et l'autre de type char
, puis nous avons passé ces tableaux aux méthodes surchargées, obtenant les résultats corrects.
D'ailleurs, vous avez déjà rencontré des méthodes surchargées auparavant.
Par exemple, la méthode String
substring()
est surchargée et peut avoir soit un paramètre, int beginIndex
, soit deux paramètres, int beginIndex, int endIndex
.
La surcharge de méthodes est très utile et est couramment utilisée en pratique.
Merci pour vos commentaires !