Total members 11893 |It is currently Fri Nov 15, 2024 8:51 am Login / Join Codemiles

Java

C/C++

PHP

C#

HTML

CSS

ASP

Javascript

JQuery

AJAX

XSD

Python

Matlab

R Scripts

Weka





Java Enum defines a set of constant variables that you can use multiple times through your application. For instance, software engineers usually define constants for week's days or payment methods. Before you start using Java Enum and learning its syntax, you may need to take a careful look at the following abstract hints about Java Enum usage:
  • To define Enum type you have to use enum keyword.
  • All enums extend java.lang.Enum.
  • You can define Enum inside a class as any class member.
  • Enum can't extend (inherit ) any other type.
  • Enum type constructor must be package-private.
  • Enum declaration defines a class (called an enum type).
  • Enum class can include methods and other variables.
  • Compiler automatically adds some methods when it compile an Enum such as values() and valueOf() functions.


Remembering the hints above will boost up the speed of you as a developer getting familiar with Java Enum. But lets us start with a simple example for Java Enum usage. In the code snippet below I wrote a declaration for Java Enum of three values.

Java Enum Type Declaration and Usage Example


java code
enum PaymentTypes 
{
PREPAID, POSTPAID, NEW
}

As you surely notice, you have to start with the keyword enum followed by the name of Enum type (PaymentTypes). The name of Enum type will be used later through the Java code as a reference to that Enum type. You can add your enum declaration outside or inside the java class based on your software design. The following snippet defines the same Enum type and use the switch expression to control decision based on Enum value. I create a variable of type "PaymentTypes" with an initialization value of NEW:
java code
public class Main {
public static void main(String[] args) {
PaymentTypes currentPayType=PaymentTypes.NEW;
switch(currentPayType)
{
case PREPAID:
System.out.println("This type is prepaid");
break;
case POSTPAID:
System.out.println("This type is postpaid");
break;
case NEW:
System.out.println("This type is new");
break;
default:
System.out.println("This type is not defined!!");
break;
}
}
}
enum PaymentTypes {
PREPAID, POSTPAID, NEW
}


The output of the above ENUM example is :
java code
This type is new


Check if Java Enum Varriables are equal


In this subsection, we use the CompareTo function to compare two Enums values of the same Enum type ( note: must be of the same type). CompareTo() returns 0 (If two are equal enum variables are equal), -1 ( If second parameter is less ordered) and 1 ( if second parameter is highly ordered ) in the Enum Type definition.
java code
public class Main {
public static void main(String[] args) {
PaymentTypes newpayType=PaymentTypes.NEW;
PaymentTypes prepaidType= PaymentTypes.PREPAID;
if(newpayType.compareTo(prepaidType)==0)
{
System.out.println("The two enum values are equal and of same order");
}else if(newpayType.compareTo(prepaidType)==-1)
{
System.out.println("The two enum variables are different and second parameter is highly ordered");
}else
{
System.out.println("The two enum variables are different and second parameter is less ordered");
}
}
}
enum PaymentTypes {
PREPAID, POSTPAID, NEW
}

The output of running the snippet above is as follows:
Code:
The two enum values are different and parameter  is less ordered

The order here is the order in which the enum values are declared.


Defining Java Enum Type Constructor


In Java, you are permitted to define a constructor for your Jave Enum type. An important syntax rule of Java Enum's constructor that it has to be private. The private constructor defines the constants listed in the beginning of the Enum body. The code snippet shared below shows an example for Enum constructor:
java code
public enum CarEnum {

BMW("BMW"), TOYOTA("TOYOTA"), FIAT("FIAT");
private String CarType;

private CarEnum(String CarType) {
this.CarType = CarType;
}

public String getCarType() {
return CarType;
}
}

The question that probably will raise here is that "Why you may need to have an Enum constructor?". The private constructor purpose is exactly as a class private constructor. The private constructor is only can be accessed within the Enum body.

Access a value of Java Enum


In your java application, you may need to know how to access a value of Java Enum Type.The following code snippet shows you how to access your Enum (mycar Enum variable) in the main class:
java code
public class EnumTest {
static CarEnum mycar;
public static void main(String args[])
{
System.out.println(mycar.BMW.getCarType());
}
}


To print all values of a specific Enum Type


For each Enum class type, a function with name "values" is auto-generated by your IDE (NetBeans or Eclipse) which can be used to print all the ENUMs available.
java code
public class Main {

public static void main(String[] args) {
// To print all the values of enum type :
for (CarEnum carType : CarEnum.values()) {
System.out.println("Car type:- " + carType);
}
}
}
enum CarEnum {
BMW("BMW"), TOYOTA("TOYOTA"), FIAT("FIAT");
private String CarType;
private CarEnum(String CarType) {
this.CarType = CarType;
}
public String getCarType() {
return CarType;
}
}

Using valueOf function to return Enum


Return enum constant type if a specific declared Enum constant identifier matches the string passed to valueOf() function.
java code
public class Main {
public static void main(String[] args) {

System.out.print(CarEnum.valueOf("BMW"));
}
}
enum CarEnum {
BMW("Bavarian Motor Works"),
TOYOTA("Too Often Yankees Overprice This Auto"),
FIAT("Fabbrica Italiana Automobili Torino");
private String CarType;
private CarEnum(String CarType) {
this.CarType = CarType;
}
public String getCarType() {
return CarType;
}
}

The output of this program is :
Code:
BMW


Define Enum Type As Inner Variable (Inside a Class)


Note that Enums can't be extended. But you can define Enums inside a class like any member:
java code
public class Main {

public static void main(String[] args) {

System.out.println(new BillingAccount());
// You can access the enum as class member:
// If private access you can acces it directly as follows:
System.out.println(BillingAccount.PaymentTypes.NEW);

}
}

class BillingAccount {

enum PaymentTypes {

PREPAID, POSTPAID, NEW
}
private String billingNumber;
private String paymentType;

public BillingAccount() {
billingNumber = "32423";// Any Data
paymentType = PaymentTypes.POSTPAID.toString();
}

@Override
public String toString() {
return "paymentType= " + paymentType;

}
}


The output is :
java code
paymentType= POSTPAID
NEW

Another Example :

java code
public class EnumTest {
enum Food {
BREAD("BREAD"),CHEESE("CHEESE"),MEAT("MEAT");
private String myfood;
Food(String s)
{
myfood = s ;
}
public String getValue()
{

return myfood ;
}
}


public static void main(String args[])
{
System.out.println(Food.BREAD.myfood+" "+Food.BREAD+" "+Food.values());
new EnumTest2();
}
}
class EnumTest2 {

EnumTest2()
{
System.out.println(EnumTest.Food.BREAD);
}
}


As you probably notice the difference, you can access the Enum directly inside a static function.

The output is :
Code:
BREAD  BREAD [LEnumTest$Food;@11b86e7
BREAD


Passing Enum as Type Parameter method


In the following snippet example, I print an Enum parameter value sent to a static method.
java code
public class Main {

public static void printEnum(CarEnum carEnum)
{
System.out.println(carEnum);
}
public static void main(String[] args) {
printEnum(CarEnum.FIAT);
}
}
enum CarEnum {
BMW("BMW"), TOYOTA("TOYOTA"), FIAT("FIAT");
private String CarType;
private CarEnum(String CarType) {
this.CarType = CarType;
}
public String getCarType() {
return CarType;
}
}


The output of this snippet is:
Code:
FIAT


Extending enum in java. Can we extend (inherit) an enum type?


Extending Enums in java is not allowed. As an example suppose you have two Enums A and B. You can't do the following:

java code
enum B
{
}
enum A extends enum B
{
// Define you enum here .
}



And in the same time, you can't use implements keyword, because B is not an interface ,But if your system needs both to be the same type. For example, if you want to define one function signature to take both Enums as parameters you can do it by defining an interface and implementing it in both Enums.

java code
interface enuminterface
enum B implements enuminterface
{
}
enum A implements enuminterface

{
// Define you enum here .
}


and your signature will be written as follows :
java code
return type myfunction (enuminterface Enumparam)  ;


Please, If you found this article helpful. Please share it.



_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time

updated article.


_________________
M. S. Rakha, Ph.D.
Queen's University
Canada


Author:
Mastermind
User avatar Posts: 2715
Have thanks: 74 time
Post new topic Reply to topic  [ 2 posts ] 

  Related Posts  to : Java enum example
 Define enum in java     -  
 extending enum in java     -  
 Enum Declaration     -  
 how to use enum in jaxb unmarshalling     -  
 Define Enum inside a class     -  
 Passing Enum as Type Parameter to method     -  
 2d game in java-Monster-Java 2D Game Graphics and Animation     -  
 Java course     -  
 Using FTP in java     -  
 what is java     -  



Topic Tags

Java OOP
cron





Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com