Showing posts with label Serializable. Show all posts
Showing posts with label Serializable. Show all posts

Thursday, July 16, 2009

Enums in Java 5

Following are the advantages of using Enums:

  • Enums are type safe.
  • Enums are Serializable and Comparable by default
  • Programmers doesn’t require to do extra work of implementing toString(), equals() and hashCode(). Enums provide implementation of these by default.
  • Programmers can use Enums in switch-case statements.
  • Enums are permitted to implement to interfaces.

Java 5.0 lets you to confine a variable to have only a fixed set of predefined values. For example, a cold drink shop may want to serve cold drinks in just three sizes- SMALL, MEDIUM, and LARGE. With this simple declaration, it can be guaranteed that the compiler will stop you from assigning anything to cold drinks except SMALL, MEDIUM, and LARGE.

Syntax enum DrinkSize {SMALL, MEDIUM, LARGE};

Now, if you want to get DrinkSize, you will do something like this

DrinkSize ds = DrinkSize.SMALL;

According to sun coding convention, all constants should be in caps, although you can give these in small letters also.

One important rule you need to remember about Enums is:

They must not be declared within a method.

How to declare Enum outside a class?

enum DrinkSize { SMALL, MEDIUM, LARGE } // this cannot be

// private or protected

class Drink {
DrinkSize size;
}
public class DrinkTest {
public static void main(String[] args) {
Drink drink = new Drink ();
drink.size = DrinkSize.BIG; // enum outside class
}
}

Key point to remember here is that the enum can be declared with only public or default modifier.

How to declare Enum inside a class?

class Drink {
enum DrinkSize { SMALL, MEDIUM, LARGE }
DrinkSize size;
}
public class DrinkTest {
public static void main(String[] args) {
Drink drink = new Drink();
drink.size = Drink. DrinkSize.SMALL; // enclosing class
// name required
}
}

At the end of the enum, putting a semicolon is optional

enum DrinkSize { SMALL, MEDIUM, LARGE };