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.
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.
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:
Java1public enum Planet { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10}
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.
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:
Java1public enum Planet { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10 11 private final double mass; // in kilograms 12 private final double radius; // in meters 13 14 Planet(double mass, double radius) { 15 this.mass = mass; 16 this.radius = radius; 17 } 18}
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.
The Planet
enum includes methods that provide functionality typical for a class. For example, methods to return the mass and radius values are defined as follows:
Java1public double getMass() { 2 return mass; 3} 4 5public double getRadius() { 6 return radius; 7}
This demonstrates that enums can not only act as fixed sets of constants but also encapsulate data and behavior associated with each constant.
Enums can also have additional methods to perform operations. The surfaceGravity
method within the Planet
enum calculates a planet's surface gravity using its mass and radius:
Java1public double surfaceGravity() { 2 final double G = 6.67300E-11; // gravitational constant in m^3 kg^-1 s^-2 (E-11 signifies 10^-11) 3 return G * mass / (radius * radius); 4}
Here, the method utilizes the unified gravitational constant G
and the instance variables mass
and radius
to compute gravity.
The surfaceWeight
method calculates how much an object would weigh on the planet:
Java1public double surfaceWeight(double otherMass) { 2 return otherMass * surfaceGravity(); 3}
The surfaceWeight
method calls surfaceGravity()
and multiplies it by the object's mass (otherMass
). This illustrates how enums can encapsulate detailed behaviors and calculations related to their constants.
Here is the final, complete Planet
enum that we've developed throughout the lesson:
Java1public enum Planet { 2 MERCURY(3.303e+23, 2.4397e6), 3 VENUS(4.869e+24, 6.0518e6), 4 EARTH(5.976e+24, 6.37814e6), 5 MARS(6.421e+23, 3.3972e6), 6 JUPITER(1.9e+27, 7.1492e7), 7 SATURN(5.688e+26, 6.0268e7), 8 URANUS(8.686e+25, 2.5559e7), 9 NEPTUNE(1.024e+26, 2.4746e7); 10 11 private final double mass; // in kilograms 12 private final double radius; // in meters 13 14 Planet(double mass, double radius) { 15 this.mass = mass; 16 this.radius = radius; 17 } 18 19 public double getMass() { 20 return mass; 21 } 22 23 public double getRadius() { 24 return radius; 25 } 26 27 public double surfaceGravity() { 28 final double G = 6.67300E-11; 29 return G * mass / (radius * radius); 30 } 31 32 public double surfaceWeight(double otherMass) { 33 return otherMass * surfaceGravity(); 34 } 35}
This Planet
enum encapsulates not just the basic attributes of each planet, such as mass and radius, but also includes methods to calculate surface gravity and surface weight, making it a robust tool for planetary calculations.
Now that we have the complete Planet
enum, let's see how it can be used in a practical context:
Java1public class Main { 2 public static void main(String[] args) { 3 Planet earth = Planet.EARTH; 4 System.out.println("The mass of " + earth + " is " + earth.getMass() + " kg."); 5 System.out.println("The radius of " + earth + " is " + earth.getRadius() + " meters."); 6 } 7}
In this example, we retrieve the EARTH
constant from the Planet
enum and use it to access its getMass()
and getRadius()
methods.
Output:
1The mass of EARTH is 5.976E24 kg. 2The radius of EARTH is 6378140.0 meters.
The output shows the mass and radius values for Earth, illustrating how enum constants can encapsulate attributes and provide methods for accessing them.
This demonstrates how to leverage the methods we've defined to obtain specific information about each planet, making your code both intuitive and powerful.
Enumerations in Java are powerful because they bring several advantages:
- Type Safety: They ensure that variables of the enum type can only hold predefined values, helping to avoid errors related to invalid values.
- Code Readability: Enumerations improve readability by grouping related constants and their associated behaviors in a cohesive manner, making the code easier to understand.
- Maintainability: By encapsulating related constants and their behaviors, enums help keep the code maintainable. Changes and updates are easier to manage within a well-defined structure.
Using the Planet
enum example, we can see these advantages in action. Enums are used not just to define constants (like the mass and radius of planets) but also to associate detailed data and behavior (such as calculating surface gravity and weight) with those constants. This leads to cleaner and more maintainable code, demonstrating how enums can transform the way you write and organize your Java programs.
Ready? Let's jump into the practice section and see how enumerations can transform your code!