Surcharge de Méthode
Utilisation d'une méthode avec différents paramètres en Java
Java permet d'écrire différentes méthodes portant 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 de données. 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
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; }
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
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(); }
Ici, nous avons surchargé la méthode printArrayToTheConsole pour accepter et retourner des valeurs int et char.
Combinons maintenant 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354package 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(); } }
Deux méthodes différentes ont été surchargées en ajoutant la possibilité d'utiliser ces méthodes avec des tableaux de type char. Les noms de ces méthodes ont également été légèrement modifiés, car il est désormais possible de les surcharger plusieurs fois pour accepter et retourner des valeurs de types différents.
Pour le vérifier, deux tableaux différents ont été créés, l'un de type int et l'autre de type char, puis ces tableaux ont été passés aux méthodes surchargées, ce qui a permis d'obtenir les résultats corrects.
D'ailleurs, les méthodes surchargées ont déjà été rencontrées précédemment.
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 !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Awesome!
Completion rate improved to 2.63
Surcharge de Méthode
Glissez pour afficher le menu
Utilisation d'une méthode avec différents paramètres en Java
Java permet d'écrire différentes méthodes portant 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 de données. 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
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; }
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
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(); }
Ici, nous avons surchargé la méthode printArrayToTheConsole pour accepter et retourner des valeurs int et char.
Combinons maintenant 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354package 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(); } }
Deux méthodes différentes ont été surchargées en ajoutant la possibilité d'utiliser ces méthodes avec des tableaux de type char. Les noms de ces méthodes ont également été légèrement modifiés, car il est désormais possible de les surcharger plusieurs fois pour accepter et retourner des valeurs de types différents.
Pour le vérifier, deux tableaux différents ont été créés, l'un de type int et l'autre de type char, puis ces tableaux ont été passés aux méthodes surchargées, ce qui a permis d'obtenir les résultats corrects.
D'ailleurs, les méthodes surchargées ont déjà été rencontrées précédemment.
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 !