Java Enum Tutorial - Ten Things Coffee Devs Should Know Close Using Enum
Apart from the Class in addition to Interface, Enumeration type or Enum is about other pop type inward Java programming language. Enum allows you lot to stand upward for a fixed number of well-known things inward a type-safe vogue e.g. days of the week, days of the month, planets inward solar system, buttons on remote control, keys on keyboard in addition to suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to stand upward for the fixed number of things, known every bit enum int pattern in addition to enum string pattern every bit described inward classic Effective Java past times none other than Joshua Bloch. Though they served the purpose, they had about major drawbacks which resulted inward misfortunate lineament code.
One of the major issues was type-safety i.e. you lot cannot bound them to stand upward for a fixed number of values e.g. an integer constant, which is representing days of the calendar week tin dismiss bring value every bit 100, which is incorrect, given nosotros bring solely vii days inward a week.
These limitations are addressed past times providing enum type, which guarantees that solely right in addition to fixed number of values tin dismiss hold upward assigned to them. The proficient matter close Enum inward Java is that they are characteristic rich, the bad matter is that they are even thence under-used in addition to many developers don't fifty-fifty know close Enumeration type inward detail.
Though in that place is a lot of weblog postal service close unlike features of Enum inward Java, in addition to their usage, in that place is hardly whatever page, which provides a proficient await at key points close Enum. It doesn't hateful to hold upward comprehensive but at-least provides those lesser known details.
I had previously shared about features inward cast of question-answer on my article 15 Java Enum Interview Questions in addition to inward this post, nosotros volition larn to a greater extent than close Enum inward Java inward this article. I bring kept the explanation brusk in addition to to the betoken to it may await similar a summary in addition to notes than a tutorial, but tin dismiss hold upward really useful to chop-chop acquire up-to-speed amongst Enum type inward Java.
2. All enumeration type implicitly extends from java.lang.Enum flat internally. Which way Enums are internally represented every bit a flat type. Furthermore, enum constants are instances of the enumeration class.
There is a lot of similarity betwixt enum in addition to class in Java but in that place is too about deviation e.g. enum instances are implicitly public static final, you lot don't request to declare them, every bit explained in The Complete Java Masterclass and shown inward the next slide :
3. Since all Enum type extends java.lang.Enum, they cannot extend whatever other flat inward Java, every bit multiple inheritances are non allowed inward Java, in addition to a flat tin dismiss solely extend i class. This holding has non changed fifty-fifty amongst the introduction of default or defender methods inward Java 8, which allows you lot to declare non-abstract methods inward the interface.
4. Enum tin dismiss implement an interface inward Java, which is too a way to extend enum type. When an Enum extend an interface, each of their instance implement interface method inward their ain way or you lot tin dismiss render a default implementation nether Enum flat itself.
Take a await at this example, it's non the best but at-least demonstrate how to implement interface within enum inward Java.
You tin dismiss encounter that EnumThread, which is an enum genuinely implements Runnable interface in addition to too overrides run() method. This proves that enumeration type cannot solely implement an interface but too tin dismiss override methods inward Java. See constructor but it tin dismiss solely hold upward private. You cannot acquire inward world because Enum instances are supposed to hold upward created at compile fourth dimension in addition to from the flat itself.
Influenza A virus subtype H5N1 non-private Enum constructor amongst whatever modifier other than somebody is a compile-time fault inward Java. Though a constructor without whatever access modifier is too allowed.
Similarly, you lot tin dismiss too overload constructor within Enum, every bit shown below, past times the way, don't forget to declare enum constants or; earlier declaring constructors, you lot tin dismiss too encounter this postal service to larn to a greater extent than close Enum constructor inward Java.
6. The java.lang.Enum defines several useful methods, which is available to all enumeration type inward Java. You tin dismiss usage name() method to acquire the mention of whatever Enum constants. String literal used to write enum constants are their name.
Similarly, values() method tin dismiss hold upward used to acquire an array of all Enum constants from an Enum type in addition to you lot tin dismiss usage valueOf() method to convert whatever String to Enum constant inward Java, every bit shown below
In this code snippet, valueOf() method returns an Enum constant Gender.MALE, calling mention on that returns "MALE".
7. There are 2 ways to compare enum constants inward Java, you lot tin dismiss either usage equals() method or but == operator. There are about advantages of using == operator over equals, every bit it provides type-safety in addition to too avoids potential NullPointerException if the enum on which you lot are calling equals() is null. You tin dismiss encounter to a greater extent than details close comparison 2 Enums inward Java here.
8. Enum constants cannot hold upward cloned inward Java. An travail to brand a clone of Enum constants volition throw CloneNotSupportedException.
9. Like int, short and char, in addition to String from Java 7, Enum tin dismiss too hold upward used within switch in addition to illustration statements, every bit shown below. You tin dismiss too encounter this post to larn to a greater extent than close Enum in addition to switch illustration inward Java :
10. When you lot declare an Enum type within a class, it is past times default static. You tin dismiss encounter that from higher upward illustration that, nosotros tin dismiss access OS Enum type every bit SmartPhone.OS, which is similar accessing a static fellow member of whatever class.
11. The new() operator is non permitted to hold upward used amongst enum, non fifty-fifty within enum itself. This is because, Enum constants are fixed, in addition to no instance of an enum tin dismiss hold upward created at runtime.
12. Like whatever other class, you lot tin dismiss too override toString() method for whatever Enum type. By default toString() method returns the mention of Enum constants in addition to its output is same every bit of name() method, but you lot tin dismiss override it to render to a greater extent than information.
That's all close Enum inward Java. I promise this exceptional helps you lot to empathise Enumeration type inward Java. It's i of the primal concept, which you lot can't afford to overlook. Since I bring used Java fifty-fifty earlier enumeration type exists, I tin dismiss say that enum helps you lot to write robust in addition to produce clean code inward Java.
Further Learning
One of the major issues was type-safety i.e. you lot cannot bound them to stand upward for a fixed number of values e.g. an integer constant, which is representing days of the calendar week tin dismiss bring value every bit 100, which is incorrect, given nosotros bring solely vii days inward a week.
These limitations are addressed past times providing enum type, which guarantees that solely right in addition to fixed number of values tin dismiss hold upward assigned to them. The proficient matter close Enum inward Java is that they are characteristic rich, the bad matter is that they are even thence under-used in addition to many developers don't fifty-fifty know close Enumeration type inward detail.
Though in that place is a lot of weblog postal service close unlike features of Enum inward Java, in addition to their usage, in that place is hardly whatever page, which provides a proficient await at key points close Enum. It doesn't hateful to hold upward comprehensive but at-least provides those lesser known details.
I had previously shared about features inward cast of question-answer on my article 15 Java Enum Interview Questions in addition to inward this post, nosotros volition larn to a greater extent than close Enum inward Java inward this article. I bring kept the explanation brusk in addition to to the betoken to it may await similar a summary in addition to notes than a tutorial, but tin dismiss hold upward really useful to chop-chop acquire up-to-speed amongst Enum type inward Java.
Enum Tutorial inward Java
1. Enum is constants inward Java. They are implicitly declared public, static and final. Since they are constant, in that place is no way you lot tin dismiss alter them.2. All enumeration type implicitly extends from java.lang.Enum flat internally. Which way Enums are internally represented every bit a flat type. Furthermore, enum constants are instances of the enumeration class.
There is a lot of similarity betwixt enum in addition to class in Java but in that place is too about deviation e.g. enum instances are implicitly public static final, you lot don't request to declare them, every bit explained in The Complete Java Masterclass and shown inward the next slide :
3. Since all Enum type extends java.lang.Enum, they cannot extend whatever other flat inward Java, every bit multiple inheritances are non allowed inward Java, in addition to a flat tin dismiss solely extend i class. This holding has non changed fifty-fifty amongst the introduction of default or defender methods inward Java 8, which allows you lot to declare non-abstract methods inward the interface.
4. Enum tin dismiss implement an interface inward Java, which is too a way to extend enum type. When an Enum extend an interface, each of their instance implement interface method inward their ain way or you lot tin dismiss render a default implementation nether Enum flat itself.
Take a await at this example, it's non the best but at-least demonstrate how to implement interface within enum inward Java.
public class EnumDemo04{ public static void main(String args[]) { EnumThread thread = EnumThread.ONE; thread.run(); thread = EnumThread.TWO; thread.run(); thread = EnumThread.THREE; thread.run(); } private enum EnumThread implements Runnable{ ONE { @Override public void run() { System.out.println("ONE"); } }, TWO { @Override public void run() { System.out.println("TWO"); } }, THREE; @Override public void run() { System.out.println("Default"); } } } Output ONE TWO Default
Influenza A virus subtype H5N1 non-private Enum constructor amongst whatever modifier other than somebody is a compile-time fault inward Java. Though a constructor without whatever access modifier is too allowed.
Similarly, you lot tin dismiss too overload constructor within Enum, every bit shown below, past times the way, don't forget to declare enum constants or; earlier declaring constructors, you lot tin dismiss too encounter this postal service to larn to a greater extent than close Enum constructor inward Java.
public enum EnumWithConstructor{ ; private EnumWithConstructor(){ System.out.println("Default no-arg Enum constructor"); } EnumWithConstructor(int i){ System.out.println("Enum Constructor amongst i argument"); } // compile fourth dimension fault - illegal access modifier, // solely somebody is allowed public EnumWithConstructor(String s){ System.out.println("public constructor are non allowed within Enum inward Java"); } }
6. The java.lang.Enum defines several useful methods, which is available to all enumeration type inward Java. You tin dismiss usage name() method to acquire the mention of whatever Enum constants. String literal used to write enum constants are their name.
Similarly, values() method tin dismiss hold upward used to acquire an array of all Enum constants from an Enum type in addition to you lot tin dismiss usage valueOf() method to convert whatever String to Enum constant inward Java, every bit shown below
public class EnumDemo06{ public static void main(String args[]) { Gender fromString = Gender.valueOf("MALE"); System.out.println("Gender.MALE.name() : " + fromString.name()); } private enum Gender{ MALE, FEMALE; } } Output: Gender.MALE.name() : MALE
In this code snippet, valueOf() method returns an Enum constant Gender.MALE, calling mention on that returns "MALE".
7. There are 2 ways to compare enum constants inward Java, you lot tin dismiss either usage equals() method or but == operator. There are about advantages of using == operator over equals, every bit it provides type-safety in addition to too avoids potential NullPointerException if the enum on which you lot are calling equals() is null. You tin dismiss encounter to a greater extent than details close comparison 2 Enums inward Java here.
8. Enum constants cannot hold upward cloned inward Java. An travail to brand a clone of Enum constants volition throw CloneNotSupportedException.
9. Like int, short and char, in addition to String from Java 7, Enum tin dismiss too hold upward used within switch in addition to illustration statements, every bit shown below. You tin dismiss too encounter this post to larn to a greater extent than close Enum in addition to switch illustration inward Java :
public class EnumDemo9{ public static void main(String args[]) { SmartPhone iPhone = new SmartPhone(SmartPhone.OS.iOS); SmartPhone.OS operatingSystem = iPhone.getOS(); switch(operatingSystem){ case iOS: System.out.println("Running on iOS"); break; case Android: System.out.println("Running on Android"); break; case Windows8: System.out.println("Running on Windows8"); break; } } } class SmartPhone { public enum OS{ iOS, Android, Windows8; } private OS os; public SmartPhone(OS os){ this.os = os; } public OS getOS(){ return os; } } Output: Running on iOSYou tin dismiss clearly say that nosotros are using an enum variable within the switch() block to determination making, in addition to nosotros are too using enum constants inward illustration statements. You tin dismiss farther encounter Effective Java tertiary Edition to larn to a greater extent than close to a greater extent than advanced in addition to effective usage of Enum similar this.
10. When you lot declare an Enum type within a class, it is past times default static. You tin dismiss encounter that from higher upward illustration that, nosotros tin dismiss access OS Enum type every bit SmartPhone.OS, which is similar accessing a static fellow member of whatever class.
11. The new() operator is non permitted to hold upward used amongst enum, non fifty-fifty within enum itself. This is because, Enum constants are fixed, in addition to no instance of an enum tin dismiss hold upward created at runtime.
12. Like whatever other class, you lot tin dismiss too override toString() method for whatever Enum type. By default toString() method returns the mention of Enum constants in addition to its output is same every bit of name() method, but you lot tin dismiss override it to render to a greater extent than information.
That's all close Enum inward Java. I promise this exceptional helps you lot to empathise Enumeration type inward Java. It's i of the primal concept, which you lot can't afford to overlook. Since I bring used Java fifty-fifty earlier enumeration type exists, I tin dismiss say that enum helps you lot to write robust in addition to produce clean code inward Java.
Further Learning
The Complete Java Masterclass
see here)How to convert Enum to String in Java (click here) How to usage enum in switch illustration inward Java (see here) How to loop over Enum constants using foreach loop inward Java (link) How to usage valueOf() method of Enum inward Java (read here) How to produce enum from String in Java (read here) Practical Example of Enum inward Java (see here) How to define a constructor for Enumeration type (read here) How to implement Singleton designing using Enum in Java (check here) Difference betwixt RegularEnumSet in addition to JumboEnumSet (read here) 15 Questions to cheque your cognition close Enum inward Java (answers)
see here)
Thanks for reading this article thence far. If you lot similar this article thence delight portion amongst your friends in addition to colleagues. If you lot bring whatever questions or feedback thence delight drib a note.
0 Response to "Java Enum Tutorial - Ten Things Coffee Devs Should Know Close Using Enum"
Post a Comment