Object-Oriented Programming with Java. Enums, what is an enum? Why do we need them? Do we need them? They're very convenient, but we've lived without them for almost ten years. How do you declare an enum? How do you extend an enum? What about enums with generics? Well, first, we need to know [LAUGH] what enum is. And finally using enums in code. So, what is an enum? Here's an example. Enum Cardsuit. We have predefined the possible values. There's clubs, diamonds, spades and hearts. If you want to add some other one, well you can't. This is an enumeration of a fixed set of constant values. All you have are clubs, diamonds, spades and hearts. An enum is by definition a subclass of the enum class. But that class is generated for you by the compiler based off of your enum definition. And since it is a class, and since it is a subclass, we can add constructors. Additional data, additional methods, but there will be restrictions. And again, you can't create new instances. They are fixed as part of the enum. The enum declares what all the possible values are. So, when can you use them? Anywhere you want to represent a fixed set of constant values. Now they're not just like int or string but they're actual fixed set of constant instances, you can talk about planets. And you would enumerate all nine of them because I go that way, Pluto is a planet. And each planet would have a set of properties, its name, its ordinal value, Mercury is one, Pluto is nine, Earth is the third rock from the Sun. It would have whatever else, what is the length of a Mercurian versus Plutonian versus Earthian year? How many days to go completely around the Sun? How long is a day? How long does it take the rotate on its axis? What is it's radius? Whatever other things you wanted to say about the planet, you could add. And then I could loop over the enumeration of planets and access and print out their information. We coud do this with many other things as long as you know what the fixed set is. You could make menu items and many other things originally before Java 5, we would use something like an int. Well, this leads to a bunch of problems, first of all seasons, okay, there we got winter, spring, summer and fall. What months correspond to those? No way of saying. What's the average temperature for that particular season here? No way of adding that information if it were appropriate, because it's simply an int. And by the way, I could add winter to pi, it's just a number, not very type safe. Enumerations are type safe and they are complete instances of classes. So, they are a tremendous improvement over the old way of doing things. Before Java 5, not type safe, no namespace, anytime you wanted to add a new constant, things had to be changed. They were simply ints when you printed them out. So, you didn't have any additional information, print out Pluto nine, and that wasn't helpful. So, that's what enums are and what they help to fix.