Enums & Annotations
This lesson discusses the do's and don'ts of using enums and annotations in Java
We'll cover the following...
Notes on Enums & Annotations
Enum types are effectively final, because they don't have accessible constructors. Clients can neither create instances of an enum type nor extend it, there can be no instances but the declared enum constants. In other words, enum types are instance-controlled. You can think of them as generalization of singletons which are essentially single-element enums.
Java’s enum types are full-fledged classes, far more powerful than their counterparts in these other languages, where enums are essentially int values.
Nest enums where appropriate. If an enum is generally useful, it should be a top-level class; if its use is tied to a specific top-level class, it should be a member class of that top-level class.
Add state to enums using fields. To associate data with enum constants, declare instance fields and write a constructor that takes the data and stores it in the fields. Enums are by their nature immutable, so all fields should be final. They can be public, but it is better to make them private and provide public accessors. For example, consider the following enum of
Superheroes
. Each superhero has some data associated with it such as age, height, weight etc. We can add fields to represent this data and pass the values in the constructor as shown below:enum Superheroes { Superman(23, 200.15), Batman(24, 200), Flash(25, 150); // Flash better be thin to run that fast! int