I am clear with advanced use of enum in java. Many of the points which differentiate them from regular classes and tells their need are also clear to me.
Can anyone give some practical example with sample code for advanced enum? Which can clearly elaborate about
where we should avoid classes and should use enum instead
.
Please dont be confused. I am not asking for how to use enum or what is the use of enum. There are many questions and answers on this. I am looking for some real time/ live / practical example where we should avoid any other data type or classes.
Enums are usually used when using constants. They act as providing a type for the constant, instead of leaving them 'loose' as ints or Strings like it was being done before they were introduced.
Instead of saying :
public static final int MALE = 1;
public static final int FEMALE = 2;
You can say
public enum Gender {
MALE, FEMALE;
}
and refer to them as Gender.MALE and Gender.FEMALE.
Without enums, the method to setGender needs to accept an int (in the above example) and I can pass anything other than 1 or 2. The code in there then needs to check if the int being passed maps to the constant, etc. Enums provide a clean and easy way in such situations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With