Saturday, November 9, 2019

Java Enum Tutorial - X Things Coffee Devs Should Know Most Using Enum

Apart from the Class as well as Interface, Enumeration type or Enum is roughly other pop type inwards Java programming language. Enum allows y'all to correspond a fixed number of well-known things inwards a type-safe fashion e.g. days of the week, days of the month, planets inwards solar system, buttons on remote control, keys on keyboard as well as suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to correspond the fixed number of things, known equally enum int pattern as well as enum string pattern equally described inwards classic Effective Java past times none other than Joshua Bloch. Though they served the purpose, they had roughly major drawbacks which resulted inwards wretched character code.


One of the major issues was type-safety i.e. y'all cannot confine them to correspond a fixed number of values e.g. an integer constant, which is representing days of the calendar week tin give the axe accept value equally 100, which is incorrect, given nosotros accept exclusively vii days inwards a week.

These limitations are addressed past times providing enum type, which guarantees that exclusively right as well as fixed number of values tin give the axe live on assigned to them. The skilful affair virtually Enum inwards Java is that they are characteristic rich, the bad affair is that they are notwithstanding under-used as well as many developers don't fifty-fifty know virtually Enumeration type inwards detail.

Though at that topographic point is a lot of weblog post virtually unlike features of Enum inwards Java, as well as their usage, at that topographic point is hardly whatsoever page, which provides a skilful hold off at key points virtually Enum. It doesn't hateful to live on comprehensive but at-least provides those lesser known details.

I had previously shared roughly features inwards shape of question-answer on my article 15 Java Enum Interview Questions as well as inwards this post, nosotros volition larn to a greater extent than virtually Enum inwards Java inwards this article. I accept kept the explanation curt as well as to the indicate to it may hold off similar a summary as well as notes than a tutorial, but tin give the axe live on really useful to speedily acquire up-to-speed alongside Enum type inwards Java.




Enum Tutorial inwards Java

1. Enum is constants inwards Java. They are implicitly declared public, static and final. Since they are constant, at that topographic point is no way y'all tin give the axe alter them.


2. All enumeration type implicitly extends from java.lang.Enum course of report internally. Which way Enums are internally represented equally a course of report type. Furthermore, enum constants are instances of the enumeration class.

There is a lot of similarity betwixt enum as well as class in Java but at that topographic point is likewise roughly divergence e.g. enum instances are implicitly public static final, y'all don't remove to declare them, equally explained in The Complete Java Masterclass and shown inwards the next slide :

 Enumeration type or Enum is roughly other pop type inwards Java programming linguistic communication Java Enum Tutorial - 10 Things Java Devs Should Know virtually Using Enum




3. Since all Enum type extends java.lang.Enum, they cannot extend whatsoever other course of report inwards Java, equally multiple inheritances are non allowed inwards Java, as well as a course of report tin give the axe exclusively extend i class. This holding has non changed fifty-fifty alongside the introduction of default or defender methods inwards Java 8, which allows y'all to declare non-abstract methods inwards the interface.


4. Enum tin give the axe implement an interface inwards Java, which is likewise a way to extend enum type. When an Enum extend an interface, each of their instance implement interface method inwards their ain way or y'all tin give the axe render a default implementation nether Enum course of report itself.

Take a hold off at this example, it's non the best but at-least demonstrate how to implement interface within enum inwards 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 

You tin give the axe run into that EnumThread, which is an enum truly implements Runnable interface as well as likewise overrides run() method. This proves that enumeration type cannot exclusively implement an interface but likewise tin give the axe override methods inwards Java. See constructor but it tin give the axe exclusively live on private. You cannot become far world because Enum instances are supposed to live on created at compile fourth dimension as well as from the course of report itself.

H5N1 non-private Enum constructor alongside whatsoever modifier other than somebody is a compile-time fault inwards Java. Though a constructor without whatsoever access modifier is likewise allowed.

Similarly, y'all tin give the axe likewise overload constructor within Enum, equally shown below, past times the way, don't forget to declare enum constants or; earlier declaring constructors, y'all tin give the axe likewise run into this post to larn to a greater extent than virtually Enum constructor inwards Java.

public enum EnumWithConstructor{                  ;                 private EnumWithConstructor(){                         System.out.println("Default no-arg Enum                                           constructor");                 }                               EnumWithConstructor(int i){                         System.out.println("Enum Constructor alongside i argument");                 }                          // compile fourth dimension fault - illegal access modifier,                  // exclusively somebody is allowed                 public EnumWithConstructor(String s){                         System.out.println("public constructor                            are non allowed within Enum inwards Java");                 }  }



6. The java.lang.Enum defines several useful methods, which is available to all enumeration type inwards Java. You tin give the axe exercise name() method to acquire the advert of whatsoever Enum constants. String literal used to write enum constants are their name.

Similarly, values() method tin give the axe live on used to acquire an array of all Enum constants from an Enum type as well as y'all tin give the axe exercise valueOf() method to convert whatsoever String to Enum constant inwards Java, equally 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 advert on that returns "MALE".



7.  There are ii ways to compare enum constants inwards Java, y'all tin give the axe either exercise equals() method or only == operator. There are roughly advantages of using == operator over equals, equally it provides type-safety as well as likewise avoids potential NullPointerException if the enum on which y'all are calling equals() is null. You tin give the axe run into to a greater extent than details virtually comparison ii Enums inwards Java here.



8. Enum constants cannot live on cloned inwards Java. An endeavour to brand a clone of Enum constants volition throw CloneNotSupportedException.



9.  Like int, short and char, as well as String from Java 7, Enum tin give the axe likewise live on used within switch as well as instance statements, equally shown below. You tin give the axe likewise run into this post to larn to a greater extent than virtually Enum as well as switch instance inwards 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 iOS
You tin give the axe clearly say that nosotros are using an enum variable within the switch() block to conclusion making, as well as nosotros are likewise using enum constants inwards instance statements. You tin give the axe farther run into Effective Java third Edition to larn to a greater extent than virtually to a greater extent than advanced as well as effective exercise of Enum similar this.

 Enumeration type or Enum is roughly other pop type inwards Java programming linguistic communication Java Enum Tutorial - 10 Things Java Devs Should Know virtually Using Enum



10. When y'all declare an Enum type within a class, it is past times default static. You tin give the axe run into that from to a higher house instance that, nosotros tin give the axe access OS Enum type equally SmartPhone.OS, which is similar accessing a static fellow member of whatsoever class.


11. The new() operator is non permitted to live on used alongside enum, non fifty-fifty within enum itself. This is because, Enum constants are fixed, as well as no instance of an enum tin give the axe live on created at runtime.


12.  Like whatsoever other class, y'all tin give the axe likewise override toString() method for whatsoever Enum type. By default toString() method returns the advert of Enum constants as well as its output is same equally of name() method, but y'all tin give the axe override it to render to a greater extent than information.


 Enumeration type or Enum is roughly other pop type inwards Java programming linguistic communication Java Enum Tutorial - 10 Things Java Devs Should Know virtually Using EnumThat's all virtually Enum inwards Java. I promise this special helps y'all to empathize Enumeration type inwards Java. It's i of the primal concept, which y'all can't afford to overlook. Since I accept used Java fifty-fifty earlier enumeration type exists, I tin give the axe say that enum helps y'all to write robust as well as produce clean code inwards Java.


Further Learning
The Complete Java Masterclass
see here)
  • How to convert Enum to String in Java  (click here)
  • How to exercise enum in switch instance inwards Java (see here)
  • How to loop over Enum constants using foreach loop inwards Java (link)
  • How to exercise valueOf() method of Enum inwards Java (read here)
  • How to produce enum from String in Java (read here)
  • Practical Example of Enum inwards 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 as well as JumboEnumSet (read here)
  • 15 Questions to cheque your noesis virtually Enum inwards Java (answers)

  • Thanks for reading this article thence far. If y'all similar this article as well as thence delight portion alongside your friends as well as colleagues. If y'all accept whatsoever questions or feedback as well as thence delight driblet a note. 

    No comments:

    Post a Comment