Understanding enums
Enumerations, or enums for short, are a special type of class. Whereas with a class, you can have as many instances (of the class) as you wish; with enums, the instances are predefined and therefore restricted. Enums are very useful for situations where a finite set of values apply – for example, days of the week, seasons of the year, and directions.
This ensures type-safety because, with the help of the compiler, only the instances defined are allowed. It is always better to find an issue at compile time than runtime. For example, if you had a method that defined a String
parameter, namely direction
, then someone could invoke the method with "WESTT" (note the incorrect spelling). The compiler would not catch this error as it is a valid String
, so the error would manifest at runtime. If, however, the method parameter were an enum instead, the compiler would catch it. We will see this shortly.
There are two types of enums: simple and complex...