Enumeration or enums in java

Enumeration or enums :

Enumeration is just like a list which contains only constant type value. The items in the enumerated list are called enums.
Using enums, can help to reduce the bugs in from your code. The basic components of an enum are its constants.
Enums can be declared as their own class or as a class member while we can’t declare within any methods.

Example :
Here you will see enum declaration outside of a class.


package com.pkjavacode.com;

enum Fruit {
APPLE, MANGO, BANANA, ORANGE
}

public class EnumExample {

private Fruit name;

/**
* @auther pradeep
*/
public static void main(String[] args) {
// fruit name;
EnumExample fn = new EnumExample();
fn.name = Fruit.APPLE;
System.out.println(fn.name);
}
}

Output :
APPLE

Note : in above example enum is declared outside of a class so you can not declare with private or protected modifier
so it is must be public or default.

You can also see an enum declaration within a class.

Example :


package com.pkjavacode.com;

public class EnumExample {
enum Fruit {
APPLE, MANGO, BANANA, ORANGE
}

private Fruit name;

/**
* @auther pradeep
*/
public static void main(String[] args) {
// fruit name;
EnumExample fn = new EnumExample();
fn.name = Fruit.APPLE;
System.out.println(fn.name);
}
}

Output :
APPLE

Note : enums value can’t accept a String or int type.
Example :


enum Fruit {"apple", "mango", "banana"}

The above declaration of enum is not legal and if you will try to do that you will get syntax error by the compiler.

Declaring Constructors, Methods and Variables in an enum :

An enum is a kind of class so you can add constructor, method and variable in an enum just like you add these other
classes in java.

Example :


package com.pkjavacode.com;

enum Fruit {
APPLE(3), BANANA(12), MANGO(2);
// declare a constructor
Fruit(int number) {
this.number = number;
}

// declare an instance variable
private int number;

// declare a method
public int getNumber() {
return number;
}
}

public class EnumExample {

Fruit name;

/**
* @author pradeep
*/
public static void main(String[] args) {
// fruit name;
EnumExample fn = new EnumExample();
fn.name = Fruit.APPLE;
System.out.println("Number of apple are :" + fn.name.getNumber());
}
}

Output :
Number of apple are : 3

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s