This post originated from an RSS feed registered with Java Buzz
by Javin Paul.
Original Post: Java Enum Code Example - SoftDrinks, How to use Enum in Java
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Enum is a useful feature of Java and best way to represent fixed number
of things e.g. number of planet in solar system, number of state order can be
or simply number of days in a week. Java Enum are different than there
predecessor on other languages like C and C++, where enum is just a wrapper
around integer constant. Enum in Java is a full blown type like class and
interface, they can have constructor
(though only private constructors are permitted for Enum), they can override
methods, they can have member variables, they can even declare methods, can
implement interfaces and have specialized high performance Map and Set
implementation in form of EnumMap and EnumSet. I have
written a lot of articles in Enum, exploring it's different lesser known
features and involving some best practices, but several times I receive request
for simple Enum examples, and that's
why, I am sharing this, one of the most simple example of Enum in Java. In this
Enum example, I have used Enum to represent SoftDrink in a
convenient store. My Enum class has four types of soft drinks Coke, Pepsi, Soda and Lime. To
demonstrate Enum can have constructor and member variables, I have provided
them title and price, and to demonstrate Enum can override methods, I have
overridden toString() method, which returns custom title
passed to each SoftDrink. Apart from custom title, you can
also avail implicit name() method of Enum to get an String
representation of Enum constant, it returns exact String literal used to
declare Enum constant, for example SoftDrink.COKE.name() will
return COKE while SoftDrink.COKE.toString() will
return Coke here. Let's see the example first and later I
will explain some key things about Enum in Java.