Sunday, November 24, 2019

A Practical Illustration Of Enum Inwards Java

Enum is a useful characteristic of Java as well as the best means to correspond fixed discover of things e.g. a discover of the planet inwards the solar system, the discover of solid soil club tin hold upwards or merely a discover of days inwards a week. Java Enum is unlike than their predecessor on other languages similar C as well as C++, where the enum is exactly a wrapper roughly integer constant. Enum inwards Java is a amount blown type similar shape as well as interface, they tin stimulate got constructor (though entirely somebody constructors are permitted for Enum), they tin override methods, they tin stimulate got fellow member variables, they tin fifty-fifty declare methods, tin implement interfaces as well as stimulate got specialized high functioning Map as well as Set implementation inwards shape of EnumMap as well as EnumSet.

I stimulate got written a lot of articles inwards Enum, exploring it's unlike lesser known features as well as involving some best practices, but several times I have a asking for simple Enum examples, as well as that's why, I am sharing this, 1 of the most uncomplicated examples of Enum inwards Java. In this Enum example, I stimulate got used Enum to correspond SoftDrink inwards a convenience store. This Enum shape has 4 types of soft drinks Coke, Pepsi, Soda, as well as Lime


To demonstrate Enum tin stimulate got constructor as well as fellow member variables, I stimulate got provided them title as well as price, as well as to demonstrate Enum tin override methods, I stimulate got overridden toString() method, which returns custom championship passed to each SoftDrink. Apart from the custom title, y'all tin likewise avail implicit name() method of Enum to teach a String representation of Enum constant, it returns exact String literal used to declare Enum constant, for example, SoftDrink.COKE.name() volition render COKE spell SoftDrink.COKE.toString() volition render Coke here. 



Here is some of import points virtually Enum inwards Java, which is worth remembering equally well:


Enum is a useful characteristic of Java as well as the best means to correspond fixed discover of things e Influenza A virus subtype H5N1 Practical Example of Enum inwards Java


Let's encounter the instance root as well as subsequently I volition explicate some key things virtually Enum inwards Java.


Simple Java Enum Code Example - SoftDrink

import java.util.EnumMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory;  /**  * Java computer programme to present How to role Enum inwards Java via a Simple Example  *  * @author Javin Paul  */ public class JavaEnumExample {      private static final Logger logger = LoggerFactory.getLogger(JavaEnumExample.class);          public static void main(String args[]) {                // EnumMap is a particular high functioning map to shop Enum constrants         Map<SoftDrink, Integer> shop = new EnumMap<SoftDrink, Integer>(SoftDrink.class);                 // Let's initialize store, past times storing 10 canes of each drink         // Enum provides an implicit values() method, which tin hold upwards used to iterate over Enum         for(SoftDrink potable : SoftDrink.values()){             store.put(drink, 10);         }                 // let's impress what is inwards EnumStore              for(Map.Entry<SoftDrink, Integer> entry: store.entrySet()){             logger.debug(entry.getKey() + " Qty: " + entry.getValue() 
                  + " Price: " + entry.getKey().getPrice());         }     }           }  
public enum SoftDrink{     COKE("Coke", 75), PEPSI("Pepsi", 75), SODA("Soda", 90), LIME("Lime", 50);         // Java Enum tin stimulate got fellow member variables     private String title;     private int price; // inwards cents         // You tin declare constructor for Enum inwards Java     private SoftDrink(String title, int price){         this.title = title;         this.price = price;     }         // Enum tin stimulate got methods inwards Java        public String getTitle(){         return title;     }         public int getPrice(){         return price;     }      // Enum tin override methods inwards Java     @Override     public String toString() {         return title;     }      }  Output 2013-07-03 05:39:42,878 0    [main] DEBUG JavaEnumExample  - Coke Qty: 10 Price: 75 2013-07-03 05:39:42,878 0    [main] DEBUG JavaEnumExample  - Pepsi Qty: 10 Price: 75 2013-07-03 05:39:42,878 0    [main] DEBUG JavaEnumExample  - Soda Qty: 10 Price: ninety 2013-07-03 05:39:42,878 0    [main] DEBUG JavaEnumExample  - Lime Qty: 10 Price: 50
Enum tin hold upwards compared using == operator equally good equally equals() method, it gives a choice to role onetime for amend performance. 

Every Enum inwards Java implicitly implements java.lang.Enum (compiler does that for you), which provides some convenient methods similar the name(), values() as well as valueOf(), hither nosotros stimulate got used values() as well as a for each loop to iterate over all Enum constant, quite a neat idiom post-Java 5.

That's all on this Simple Java Enum Example. It's plenty to teach y'all started amongst Enum as well as likewise demonstrate some of the key features of Java enum. I propose looking my some other article 10 Java Enum Examples as well as next majority JavaDeveloper's Notebook for to a greater extent than information on How to accept most of Enum inwards Java.


Other Java Enum Tutorials from Blog

No comments:

Post a Comment