Contenu du cours
Java Avancé
Java Avancé
Surcharge de Méthode
Utilisation d'une méthode avec différents paramètres
Java permet d'écrire différentes méthodes avec le même nom. Ces méthodes peuvent avoir des types de retour et/ou des types de paramètres différents. Cela permet d'utiliser ces méthodes avec différents types. Prenons l'exemple d'une méthode pour afficher un tableau :
Nous pouvons écrire cette méthode pour accepter des valeurs de type int
, mais que faire si nous devons afficher un tableau de type char
? Devons-nous écrire une méthode avec un nom différent ?
Java propose la surcharge de méthodes à cet effet.
Examinons un exemple d'affichage de données et d'inversion d'un tableau du chapitre précédent :
Main.java
// 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
.
Surchargeons maintenant la méthode pour afficher un tableau à l'écran. Cette méthode doit également accepter et retourner les types int
et char
:
Main.java
// 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 de type int
et char
.
À présent, 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.java
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 désormais les surcharger plusieurs fois pour accepter et retourner des valeurs de types différents.
Pour le vérifier, 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 ainsi les résultats corrects.
D'ailleurs, vous avez déjà rencontré des méthodes surchargées auparavant.
Par exemple, la méthode String
de 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 couramment utilisée en pratique.
Merci pour vos commentaires !