2

I am clear with advanced use of enum in java. Many of the points which differentiate them from regular classes and tells their need are also clear to me.

Can anyone give some practical example with sample code for advanced enum? Which can clearly elaborate about

where we should avoid classes and should use enum instead

.

Please dont be confused. I am not asking for how to use enum or what is the use of enum. There are many questions and answers on this. I am looking for some real time/ live / practical example where we should avoid any other data type or classes.

Amit Kumar Gupta
  • 7,193
  • 12
  • 64
  • 90
  • 1
    Uhh... enums and classes don't overlap. Are you sure you're not thinking of *structs* and classes? – Chris Eberle May 11 '11 at 04:12
  • 1
    @Chris - this is Java, not C or C++. – wkl May 11 '11 at 04:13
  • @birryree: good point, actually I was getting my java and C# confused there. – Chris Eberle May 11 '11 at 04:23
  • links to grab idea about concepts http://stackoverflow.com/questions/481068/when-to-use-enum-or-collection-in-java and http://www.javapractices.com/topic/TopicAction.do?Id=1 and http://java.dzone.com/blogs/mrjohnsmart/2008/05/19/a-short-primer-java-enums-part – Amit Kumar Gupta May 11 '11 at 04:43

8 Answers8

3

Enums are usually used when using constants. They act as providing a type for the constant, instead of leaving them 'loose' as ints or Strings like it was being done before they were introduced.

Instead of saying :

public static final int MALE = 1;
public static final int FEMALE = 2;

You can say

  public enum Gender {
     MALE, FEMALE;
   } 

and refer to them as Gender.MALE and Gender.FEMALE.

Without enums, the method to setGender needs to accept an int (in the above example) and I can pass anything other than 1 or 2. The code in there then needs to check if the int being passed maps to the constant, etc. Enums provide a clean and easy way in such situations.

lobster1234
  • 7,679
  • 26
  • 30
  • thanks for your response. But concepts about enum and its use are very clear to me. I am just confused about its use in some live/practical application – Amit Kumar Gupta May 11 '11 at 04:26
  • Have you been programming in Java for a while? If so, think about how you have been declaring constants, like male/female, or names of cities, basically anything that is 'enumerated' or has a fixed set of values. Most likely you've been using Strings, or ints to assign value to every constant. By using Enums, you can type-safe these enumerations. You should look at http://java.dzone.com/blogs/mrjohnsmart/2008/05/14/short-primer-java-enums-part-1 which is fairly old but walks you through Enums and how they work/why they're needed. There is a part-2 talking about advanced applications of Enums. – lobster1234 May 11 '11 at 04:29
3

you can consider this as a real-world example--

public class EnumExample
{
    public static  enum APP_STATUS{
        ALL_GOOD(1, "All things are going good"),
        WARNING(2, "SOMETHING IS BAD"),
        ERROR(3, "Its an Error"),
        FATAL(4, "Its crashed");

        private String  statusMessage;
        private int statusId;
        private APP_STATUS(int statusId, String statusMessage){
            this.statusId = statusId;
            this.statusMessage = statusMessage;
        }

        public int getStatusId(){
            return statusId;
        }

        public String getStatusMessage(){
            return statusMessage;
        }

        public boolean isAttentionRequired(){
            if(statusId<3)
                return false;
            else
                return true;
        }
    }

    public void handleAppStatusChange(APP_STATUS newStatus){
        if(newStatus.isAttentionRequired()){
            //notify admin
        }
        //Log newStatus.getStatusId() in the logfile
        //display newStatus.getStatusMessage() to the App Dash-Board
    }

    public void Test(){
        handleAppStatusChange(APP_STATUS.ALL_GOOD);
        handleAppStatusChange(APP_STATUS.WARNING);
        handleAppStatusChange(APP_STATUS.FATAL);
    }
}

(I am assuming that you know all the basics of enum.. and so, I am not explaining them here)

Nirmit Shah
  • 758
  • 4
  • 10
2

Try this example:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

Usage:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY: System.out.println("Mondays are bad.");
                         break;

            case FRIDAY: System.out.println("Fridays are better.");
                         break;

            case SATURDAY:
            case SUNDAY: System.out.println("Weekends are best.");
                         break;

            default:     System.out.println("Midweek days are so-so.");
                         break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();          

    }
}
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
  • @OD: this is a very simple example. I was looking for an example that can present use of advanced enum including its data & methods – Amit Kumar Gupta May 11 '11 at 04:24
  • 1
    @articlestack: thats the usage of Enums in java, try this link: http://www.basilv.com/psd/blog/2006/advanced-uses-of-java-5-enums – CloudyMarble May 11 '11 at 04:34
1

http://www.devdaily.com/java/using-java-enum-examples-tutorial

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

You should look at Chapter 6 Enums and Annotations (maybe best practices for Java Enum) of Effective Java (2nd Edition), the author (Joshua Bloch) of this book is also author of JDK's Enum, EnumSet, EnumMap.

Or you can look at conference of Joshua Bloch, either one :
- Google I/O 2008 - Effective Java Reloaded
- Effective Java - Still Effective After All These Years

lschin
  • 6,745
  • 2
  • 38
  • 52
1

Check out this as well some additional

Enums with constructors

enum enumConstr {
HUGE(10), OVERWHELMING(16), BIG(10,"PONDS");//(;)Compulsory

int ounces; String name;
enumConstr(int ounces){ this.ounces = ounces; }

enumConstr(int ounces,String name){
    this.ounces = ounces;
    this.name = name;
}

public int getOunces(){  return ounces; }
public String getName(){ return name; }
}//Enum completes

public class EnumWithConstr {
enumConstr size;

public static void main(String[] args) {
    EnumWithConstr constr = new EnumWithConstr();
    constr.size = enumConstr.BIG;

    EnumWithConstr constr1 = new EnumWithConstr();
    constr1.size = enumConstr.OVERWHELMING;

    System.out.println(constr.size.getOunces());//8
    System.out.println(constr1.size.getOunces());//16
    System.out.println(constr.size.getName());//PONDS
    System.out.println(constr1.size.getName());//null
}

}

 You can NEVER invoke an enum constructor directly. The enum constructor is invoked automatically, with the arguments you define after the constant value.

 You can define more than one argument to the constructor, and you can overload the enum constructors, just as you can overload a normal class constructor.

ponds
  • 2,017
  • 4
  • 16
  • 11
1

The simplest example of where an enum should used in preference to a class is a singleton

enum Singleton {
   INSTANCE
}

The instances is lazily loaded and thread safe because classes are lazily loaded and their initialisation is thread safe.

This is far simpler than using a regular class.


For a utility class I use an enum well, but this is not so common.

enum Utility {;
   public static returnType utilityMethod(args) { ... }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

When you know values are well-defined, fixed set of values which are known at compile-time.

You can use an enum as a set very easily (with EnumSet) and it allows you to define behaviour, reference the elements by name, switch on them etc.

Umesh K
  • 13,436
  • 25
  • 87
  • 129