Understanding Enumeration
Understanding Enumerations
Welcome! Before we dive into Object-Oriented Programming, this lesson will introduce you to enumerations, commonly known as enums. You may have seen enums being used to represent a fixed set of constants, such as the days of the week or directions (NORTH, SOUTH, EAST, WEST). In this lesson, we'll explore how to define and utilize enums, setting the foundation for future topics, including design patterns.
What You'll Learn
In this lesson, you'll learn how to create and use enumerations in Java. We will:
- Define an enumeration to represent a collection of constants.
- Implement constructors and methods within an
enum. - Use enumerations in your code to access constants and methods.
Using the Planet example, you'll understand how enumerations can simplify coding logic and enhance code readability.
Defining the Enumeration
The code begins by defining the Planet enum with constants for each planet. An enum in Java is a special data type that allows a variable to be one of a set of predefined constants. Each constant in the Planet enum represents a distinct planet and is instantiated with specific mass and radius values:
Each constant (MERCURY, VENUS, etc.) is an instance of the Planet enum, initialized with a specific mass and radius. Declaring these constants ensures that the set of values for Planet is fixed and known at compile time.
Constructor and Fields
Enums in Java can also have fields, methods, and constructors. Below is the Planet enum with private fields used to store the mass and radius of each planet:
These fields are declared as final, meaning they are immutable once initialized. This immutability is crucial because it ensures that the values associated with each constant do not change after they are set, preserving the integrity and consistency of the constants throughout the application's lifecycle.
The constructor Planet(double mass, double radius) is invoked for each enum constant to assign the specific mass and radius values.
