Tuesday, January 17, 2006

Java Tiger Enum Example

package LangBasics.Enum;

import java.util.Scanner;

class EnumWithMethod
{
//You can declare the method abstract in the enum type and override it
//with a concrete method in each constant.
//Such methods are known as constant-specific methods

public enum MathEnumWithMethods {
ADD {
void doCalc(int i,int j)
{
System.out.println("+ -->");
System.out.println(i + j);
}
},
SUB {
void doCalc(int i,int j)
{
System.out.println("- -->");
System.out.println(i - j);
}
},
MUL {
void doCalc(int i,int j)
{
System.out.println("* -->");
System.out.println(i * j);
}
},
DIV {
void doCalc(int i,int j)
{
System.out.println("/ -->");
if(j!=0)
System.out.println(i / j);
else
System.out.println("Not a valid input");
}
};

abstract void doCalc(int x, int y);

} // end of : MathEnumWithMethods method

public static void main(String[] args)
{
EnumWithMethod objEnumeration = new EnumWithMethod();
Scanner in = new Scanner(System.in);
System.out.println("Enter First Number");
int i = in.nextInt();
System.out.println("Enter Second Number");
int j = in.nextInt();
System.out.println("Enter Operation ADD/SUB/MUL/DIV");
String strOper = in.next();
if(strOper.equalsIgnoreCase("ADD")){

MathEnumWithMethods.ADD.doCalc(i,j);

}else if(strOper.equalsIgnoreCase("SUB")){

MathEnumWithMethods.SUB.doCalc(i,j);

}else if(strOper.equalsIgnoreCase("MUL")){

MathEnumWithMethods.MUL.doCalc(i,j);

}else if(strOper.equalsIgnoreCase("DIV")){

MathEnumWithMethods.DIV.doCalc(i,j);

}else{
System.out.println(strOper + " is not a right choice");
}

} // end of : main method

} // end of : EnumWithMethod Class

Comments:
good one ..But my questions(and suggestions) are,

a) Why java introduced this concept in JAVA 5, not in JAVA 1 ?

b) If you say example, it should be simple(just 10 lines of code)..but after i saw yr program i lost my interest!!! (don't say, In java its the case :-))

c) When you say Enum, write some history(in C/C++) about Enum or description..don't enter into CODE in the first line itself.
 
Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]