Possible Duplicate:
Understanding Enums in Java
Why should we use enums rather Java constants?
I have read that Java enums gives type safety. Can somebody please elaborate it? Or there is any other advantage of using enum over constants?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To quote http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html:
when you have this method:
you know that the argument is always going to be a day.
Compare to this:
you could pass anything to this method:
Using an
enum(or any type, such as a class or interface) gives you type safety: the type system makes sure you can only get the kind of type you want. The second example is not type safe in that regard, because your method could get any int as an argument, and you don’t know for sure what the int value means.Using the enum is a contract between the calling code and the code being called that a given value is of a given type.