We can make use of enumerations, when we need some constant values. Example is in coffee shop we may have only three types of coffee mugs like small, medium and large. In such a situation enumeration will reduce the possibility of errors. Let's see how to use enumerations in our code.
There are some rules that you have to follow while using enumerations.
1. Enumerations can be defined outside of class but with public access modifier only (It may be without access modifier i.e. default access).
2. You can define enumerations inside class with public, private, protected and static modifires only.
3. You can't define enumerations in methods.
Now let's see example of this,
enum Outer {
SMALL, MID, LARGE
}//enum Size
class MainClass {
enum Inner {
SMALL, MID, LARGE
}//enum Size
public static void main(String args[]) {
System.out.print("\nOuter enum : " + Outer.LARGE + "\nInner enum : " + Inner.LARGE);
}//PSVM
}//MainClass
Now we can continue looking more features of enumerations,
4. You can place constructors in enum class and can overload those constructors.
5. You can have variables in enum class.
6. You can have getter and setter methods in enum class
Let's see example of this,
enum Outer{
SMALL(8), MID(10), LARGE(15);
private int value;
private Outer(int value) {
this.value = value;
}//Outer
public int getValue() {
return value;
}
}//enum Outer
class MainClass {
enum Inner {
SMALL, MID, LARGE
}//enum Size
public static void main(String args[]) {
System.out.print("\nOuter enum : " + Outer.LARGE.getValue() + "\nInner enum : " + Inner.LARGE);
}//PSVM
}//MainClass
Another important thing is that you can't place enums in static block. They can be placed only in top level class, interface or outside of everything i.e. as independent But you can place enum in static inner class. Here is example of that,
class MainClass {
static class InnerClass {
enum Inner
{
SMALL, MID, LARGE
}//enum Size
}
public static void main(String args[]) {
System.out.print("\nInner enum : " + InnerClass.Inner.LARGE);
}//PSVM
}//MainClass
Even following peace of code is valid,
interface OuterInterface {
enum OuterEnum {
SMALL
}//OuterEnum
static interface InnerInterface {
enum InnerEnum {
SMALL
}//InnerEnum
}//InnerInterface
}//OuterInterface
You can explore this with all combinations.
No comments:
Post a Comment