English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce tutoriel, nous allons apprendre à comprendre la valeur string des constantes d'enumération. Nous allons également apprendre à réécrire la valeur string par défaut des constantes d'enumération à l'aide d'exemples.
Assurez-vous d'avoir déjà comprisEnumération Java.
En Java, nous pouvons utiliser la méthode toString() ou name() pour obtenir la représentation string des constantes d'enumération. Par exemple,
enum Size {}} SMALL, MEDIUM, LARGE, EXTRALARGE } class Main { public static void main(String[] args) { System.out.println("La valeur string de SMALL est "); + Size.SMALL.toString()); System.out.println("La valeur string de MEDIUM est "); + Size.MEDIUM.name()); } }
Output result
La valeur string de SMALL est SMALL La valeur string de MEDIUM est MEDIUM
Dans l'exemple ci-dessus, nous avons vu que la représentation string par défaut des constantes d'enumération est le nom de la constante en elle-même.
Nous pouvons modifier la représentation string par défaut des constantes d'enumération en réécrivant la méthode toString(). Par exemple,
enum Size {}} SMALL { //Override toString() to SMALL public String toString() { return "The size is small."; } }, MEDIUM { //Override toString() to MEDIUM public String toString() { return "The size is medium."; } }; } class Main { public static void main(String[] args) { System.out.println(Size.MEDIUM.toString()); } }
Output result
The size is medium.
In the above program, we created an enumeration Size. And we have overridden the toString() method of enumeration constants SMALL and MEDIUM.
Note:We cannot rewrite the name() method. This is because the name() method is of final type.