Java enums over Constants -
possible duplicate:
understanding enums in java
why should use enums rather java constants?
i have read java enums gives type safety. can please elaborate it? or there other advantage of using enum on constants?
to quote http://docs.oracle.com/javase/tutorial/java/javaoo/enum.html:
public enum day { sunday, monday, tuesday, wednesday, thursday, friday, saturday }
when have method:
public enumtest(day day) { this.day = day; }
you know argument going day.
compare this:
const int monday = 1; const int tuesday = 2; const int cat = 100; const int dog = 101;
you pass anything method:
public enumtest(int day) { this.day = day; }
using enum
(or type, such class or interface) gives type safety: type system makes sure can kind of type want. second example not type safe in regard, because method int argument, , don't know sure int value means.
using enum contract between calling code , code being called given value of given type.
Comments
Post a Comment