CSCI111: Chapter 6 revisited

CSCI111: Chapter 6 revisited
Enumeration (with some Ch. 3 and 12)

I lied to you earlier.

I told you that Java had two main types of things.

I said they were either

  1. a primitive data type or
  2. a class

Since version 1.5, java has provided another "type" of object, the Enum. All the enum's that you define, by default inherit from java.lang.Enum

API java.lang (version 1.4 - no Enum)
API 1.5 add Enum      See how it implements the Interface Comparable<E>? Discuss.
The <E> syntax tells you that the interface is generic. Briefly discuss Collections and the need for Generics.

An enumerated type is a special kind of class. The values of the enumerated type are a fixed set of constants (by default) and are objects. The values are, in fact, instances of its own enumerated type.

enums can be defined inside your everyday class:

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}
and can be used in switch statements or in the for-each construct to iterate over the values of an enum type (as in Java Tutorial on enum)

And/or they can be defined as a "whole" class in a .java file with additional methods and other fields. Every enumerated type contains a static method named values() that returns a list of all possible values for that type.

Textbook examples

Note: The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.

Check out the Planet example in the tutorial. It is interesting.