Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Surcharge de Méthode | Méthodes
Java Étendu
course content

Contenu du cours

Java Étendu

Java Étendu

1. Structure Java Approfondie
2. Méthodes
3. Chaîne Avancée
4. Classes
5. Classes Avancées

book
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 :

java

Main

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; }

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 :

java

Main

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(); }

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 :

java

Main

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(); } }

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.

Combien de fois pouvons-nous surcharger une méthode ?

Combien de fois pouvons-nous surcharger une méthode ?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 6
We're sorry to hear that something went wrong. What happened?
some-alt