A Pattern for Extending Java Enums

by
Lance Finney, Principal Software Engineer
Object Computing, Inc. (OCI)

Introduction

java.lang.Enum was added to Java™ in Java SE 5 in order to provide a type-safe restricted list of constants. Java's enums are more flexible than the enumeration constructs in many other languages in that each enum instance is a full-blown Object, with the ability to implement properties and logic.

However, there are some areas in which Java's enums are restricted - enum instances implicitly extend java.lang.Enum, are implicitly final, and cannot be defined using generics. This means that a developer cannot directly create an enum that contains all the instances of another, cannot inherit logic from an abstract parent, and cannot be typed for generics.

There is a petition to modify Java in future versions to support these features. In the meantime, we need to use workarounds. This article presents a pattern that can be used to simulate multiple enum types inheriting behavior from a common abstract superclass.

Setting up the Example

Imagine that you are writing an application to model solar systems, in which basic data about each celestial body would be used to calculate other physical and orbital parameters. For example, you might start with the mass, radius, and semi-major axis of the star, some planets, and some moons to calculate the length of planets' and moons' orbital periods and the surface gravity of all of the bodies. Below is some code that might be used to calculate them:

Common Superclass

package com.ociweb.sett.initial;

/**
 * A common abstract superclass for celestial bodies.
 */
public class CelestialBody {
    /**
     * The Gravitational Constant, used for calculations: 6.67300e-11
     * m³/(kg·s²).
     */
    public static final double GRAVITATIONAL_CONSTANT = 6.67300e-11;

    private final String name;
    private final double mass; // mass in kg
    private final double radius; // radius in m
    private Satellite[] satellites;

    protected CelestialBody(String name, double mass, double radius) {
        this.name = name;
        this.mass = mass;
        this.radius = radius;
    }

    /**
     * @return the surface gravity, in m/s²
     */
    public double getSurfaceGravity() {
        return GRAVITATIONAL_CONSTANT * mass / Math.pow(radius, 2.0);
    }

    /**
     * @return the mass of this celestial body, in kg
     */
    public final double getMass() {
        return mass;
    }

    /**
     * @param satellites an array containing the satellites which orbit this
     *                   celestial body, or null if this celestial body has no
     *                   satellites
     */
    public void setSatellites(Satellite[] satellites) {
        this.satellites = satellites;
    }

    /**
     * @return an array containing the satellites which orbit this celestial
     *         body, or null if this celestial body has no satellites
     */
    public final Satellite[] getSatellites() {
        return satellites;
    }

    /**
     * @return the name of this celestial body
     */
    public final String getName() {
        return name;
    }
}

Definition of Satellites (Planets and Moons)

package com.ociweb.sett.initial;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * A class representing a generic satellite (planet, moon, etc.).
 */
public final class Satellite extends CelestialBody {
    private final CelestialBody parentBody;
    private final double semiMajorAxis; // in m

    public Satellite(String name, CelestialBody parentBody, double mass,
            double radius, double semiMajorAxis) {
        super(name, mass, radius);
        this.parentBody = parentBody;
        this.semiMajorAxis = semiMajorAxis;
    }

    /**
     * @return the celestial body around which this celestial body orbits
     */
    public CelestialBody getParentBody() {
        return parentBody;
    }

    /**
     * @return the orbital period, in seconds
     */
    public double getOrbitalPeriod() {
        return 2 * Math.PI * Math.sqrt(Math.pow(semiMajorAxis, 3.0) /
                (GRAVITATIONAL_CONSTANT * parentBody.getMass()));
    }

    /**
     * Prints a summary of the calculated orbital and physical characteristics
     * of this class and any of its own satellites.
     */
    public void printSummary() {
        System.out.println("Summary for " + getParentage());

        long orbitalPeriod = (long) getOrbitalPeriod();
        System.out.printf("Orbital Period: %1$d hours/%2$d days\n",
                TimeUnit.SECONDS.toHours(orbitalPeriod),
                TimeUnit.SECONDS.toDays(orbitalPeriod));

        System.out.printf("Surface Gravity: %1$e m/s²\n\n",
                getSurfaceGravity());

        Satellite[] satellites = getSatellites();
        if (satellites != null) {
            for (Satellite child : satellites) {
                child.printSummary();
            }
        }
    }

    /**
     * Generates and returns a String listing all the orbital parents of this
     * body. So, for the Earth's moon, it would return ", satellite of EARTH,
     * satellite of SOL".
     *
     * @return a String showing orbital parentage
     */
    private String getParentage() {
        List<CelestialBody> parents = new ArrayList<CelestialBody>();
        CelestialBody parentBody = this.parentBody;
        parents.add(parentBody);
        while (parentBody instanceof Satellite) {
            Satellite satelliteParent = (Satellite) parentBody;
            parentBody = satelliteParent.getParentBody();
            parents.add(parentBody);
        }

        StringBuilder sb = new StringBuilder(getName());
        for (CelestialBody parent : parents) {
            sb.append(", satellite of ");
            sb.append(parent.getName());
        }
        sb.append(":");

        return sb.toString();
    }

}

Main execution class that sets up relationships and prints the summary

package com.ociweb.sett.initial;

/**
 * The main class for this example, it prints a summary of the Solar System
 * (using only the inner planets for simplicity).
 */
public class SolarSystem {

    public static void main(String[] args) {
        CelestialBody sol = new CelestialBody("SOL", 1.98892e30, 6.955e8);
        Satellite mercury = new Satellite("MERCURY", sol, 0.3302e24, 2.4397e6,
                57.91e9);
        Satellite venus = new Satellite("VENUS", sol, 4.869e24, 6.0518e6,
                108.21e9);
        Satellite earth = new Satellite("EARTH", sol, 5.9742e24, 6.3781e6,
                149.6e9);
        Satellite luna = new Satellite("LUNA", earth, 0.07349e24, 1.7381e6,
                0.3844e9);
        earth.setSatellites(new Satellite[]{luna});
        Satellite mars = new Satellite("MARS", sol, 0.64185e24, 3.3962e6,
                227.92e9);
        Satellite phobos = new Satellite("PHOBOS", mars, 1.072e16, 1.11e4,
                9.38e6);
        Satellite deimos = new Satellite("DEIMOS", mars, 1.5e15, 6.2e4,
                2.346e7);
        mars.setSatellites(new Satellite[]{phobos, deimos});
        sol.setSatellites(new Satellite[]{mercury, venus, earth, mars});

        printSummary(sol);
    }

    /**
     * Prints a summary for the star's solar system.
     *
     * @param star the star to be examined
     */
    public static void printSummary(CelestialBody star) {
        System.out.println("Summary for " + star.getName() + ":");
        System.out.printf("Surface Gravity: %1$e m/s²\n\n",
                star.getSurfaceGravity());

        for (Satellite satellite : star.getSatellites()) {
            satellite.printSummary();
        }
    }
}

Execution Result

> Summary for SOL:
> Surface Gravity: 2.743748e+02 m/s²
>
> Summary for MERCURY, satellite of SOL:
> Orbital Period: 2111 hours/87 days
> Surface Gravity: 3.701906e+00 m/s²
>
> Summary for VENUS, satellite of SOL:
> Orbital Period: 5392 hours/224 days
> Surface Gravity: 8.871392e+00 m/s²
>
> Summary for EARTH, satellite of SOL:
> Orbital Period: 8766 hours/365 days
> Surface Gravity: 9.799823e+00 m/s²
>
> Summary for LUNA, satellite of EARTH, satellite of SOL:
> Orbital Period: 658 hours/27 days
> Surface Gravity: 1.623304e+00 m/s²
>
> Summary for MARS, satellite of SOL:
> Orbital Period: 16484 hours/686 days
> Surface Gravity: 3.713369e+00 m/s²
>
> Summary for PHOBOS, satellite of MARS, satellite of SOL:
> Orbital Period: 7 hours/0 days
> Surface Gravity: 5.805905e-03 m/s²
>
> Summary for DEIMOS, satellite of MARS, satellite of SOL:
> Orbital Period: 30 hours/1 days
> Surface Gravity: 2.603928e-05 m/s²

The calculation of the surface gravity of each celestial body is performed in CelestialBody. Satellite has the calculation for the orbital period, along with much of the logic necessary to print the summary.

Unfortunately, SolarSystem is a very awkward class. Most of it involves setting up the definition of the SolarSystem and the relationship between the Sun, the planets, and the moons. Since we have a set number of planets and moons (ignoring for the purposes of this article the continued discovery of more moons), this seems to be a perfect place to introduce some enums:

package com.ociweb.sett.initial;

/**
 * A enumeration to define stars at the center of solar systems.
 */
public enum Star {
    SOL
}
package com.ociweb.sett.initial;

/**
 * An enumeration of the planets in our solar system. We only show the inner
 * planets, for simplicity.
 */
public enum Planet {
    MERCURY, VENUS, EARTH, MARS
}
package com.ociweb.sett.initial;

/**
 * An enumeration of the moons that orbit the Earth.
 */
public enum EarthMoon {
    LUNA
}
package com.ociweb.sett.initial;

/**
 * An enumeration of the moons that orbit Mars.
 */
public enum MarsMoon {
    PHOBOS, DEIMOS
}

Unfortunately, these two sets of code are independent: we have a type-safe grouping of stars, planets, and each set of moons in one spot, and we have logic that applies to all of these groupings in another spot. How do we combine them?

In an ideal world

In an ideal world, we would be able to combine the properties and logic we have for celestial bodies and satellites with their enumerations by having Star and Satellite extend CelestialBody with Planet, EarthMoon, and MarsMoon extending Satellite. That way, we would have our type-safe restricted set of planets or moons, and they would each get to share the property and behavior definitions that are common between them. Unfortunately, though, an enum type implicitly extends java.lang.Enum, so we can't have our enums extend Satellite.

Another ideal implementation might be to have an abstract Satellite enum that defines the properties and behavior that Planet, EarthMoon, and MarsMoon. Unfortunately, we are again stymied, because all enums are implicitly final.

Note: while this limitation is true for enums based on java.lang.Enum, it was not true for some third-party Enum implementations that pre-date Java 5. If you want to explore one of those, check out net.java.dev.reusablecomponents.lang.Enum.

Extending the Enum through Interfaces

Although we can't combine the enums and the CelestialBody logic in a form as easy as the ideal world implementations imagined above, we can still combine them using an interface and some inner classes.

Essentially, we separate the base property declarations from the calculation logic; we move the property declarations into interfaces and move concrete method implementations into helper classes.

Thus, instead of sharing a common abstract superclass that provides properties and logic, the enums will share a common Properties interface. There will then be a common inner implementation of the Properties interface that can be overriden. Additionally, we will move some of the logic into static utility delegate classes.

Updating the Example

CelestialBody

To see this in action, let's start with the new CelestialBody. In the initial version, this CelestialBody was a class with four property fields (name, mass, radius, and the satellites) and a method that calculated a physical property (getSurfaceGravity()). In the new version, it's an interface that includes and inner interface to expose those same four properties and a static utility inner class to calculate the physical property:

There's enough code here to need to look at the individual parts one-by-one. First, we'll look at the outer interface, CelestialBody. This is the interface that is implemented by enums like Star and extended by interfaces like Satellite.

package com.ociweb.sett;

/**
 * An interface for defining celestial bodies (start, planets, moons, etc.).
 */
public interface CelestialBody {
    /**
     * The Gravitational Constant in units of m³/(kg·s²).
     */
    public static final double GRAVITATIONAL_CONSTANT = 6.67300e-11;

    Properties getProperties();

    < ...snip inner interfaces and classes...>
}

There's actually very little code here. We declare the gravitational constant here because it will be used by all of the children, but it could really be defined anywhere.

In contrast, getProperties() is key to this entire pattern. It provides access to the inner interface Properties, which we will look at next. This is not strictly necessary - we could combine the interfaces. However, Properties has lots of methods, and the inability to provide an abstract superclass for the child enums means that each of the children would have to implement all the methods. Since most of the implementations are identical, this would involve a significant amount of duplicated boilerplate code. By extracting those methods into a separate interface, we can provide a shared delegate implementation.

Through this method, clients of the SolarSystem API will be able to access all the necessary information about the relationships between bodies and the logic used to calculate the physical properties. We're partially decoupling the body definition from the physical attributes, so that we can use enums for the type-safe declarations without being hobbled too much by enum's restrictions.

Next, let's look at the Properties interface that is accessed through the getter mentioned above:

interface Properties {
    /**
     * @return the mass of this celestial body, in kg
     */
    double getMass();

    /**
     * @return the radius of this celestial body, in m.
     */
    double getRadius();

    /**
     * @return an array containing the satellites which orbit this
     *     celestial body, or null if this celestial body has no satellites
     */
    Satellite[] getSatellites();

    /**
     * Returns the name of this celestial body. Implementation of this
     * method can be provided by {@link Enum}.
     *
     * @return the name of this celestial body
     */
    String name();

    /**
     * Prints a summary for the celestial body and any satellites it has.
     */
    void printSummary();
}

The methods declared here are mostly the methods exposed in the old version of CelestialBody, with the addition of moving printSummary() into here. In the old version, there wasn't a good way to share printing behavior between the different classes because Star and Planet weren't related. Now we can.

The Properties inner interface is represented by ImmutableProperties, a concrete immutable representation. The immutable representation is necessary because the Properties instance is a property of the enum instance, and enum instances must be immutable constants, by definition. The enum instances will be holding onto a Properties object. If a caller were able to modify the state of a Properties instance in such a way that it modified the version held by the enum, then two distinct copies of the same enum instance would have different state. That is unacceptable.

/**
 * An immutable representation of the properties of the {@link
 * CelestialBody}. Immutability is necessary to honor the contract for
 * enums.
 */
static final class ImmutableProperties implements Properties {
    private final double mass;
    private final double radius;
    private final String name;
    private final Satellite[] satellites;

    public ImmutableProperties(String name, double mass, double radius,
            Satellite... satellites) {
        this.name = name;
        this.mass = mass;
        this.radius = radius;
        this.satellites = satellites == null ? null : satellites.clone();
    }

    @Override
    public double getMass() {
        return mass;
    }

    @Override
    public double getRadius() {
        return radius;
    }

    @Override
    public Satellite[] getSatellites() {
        return satellites == null ? null : satellites.clone();
    }

    @Override
    public String name() {
        return name;
    }

    public void printSummary() {
        System.out.println("Summary for " + name() + ":");
        System.out.printf("Surface Gravity: %1$e m/s²\n\n",
                Util.calcSurfaceGravity(this));

        if (satellites != null) {
            for (Satellite satellite : getSatellites()) {
                satellite.getProperties().printSummary();
            }
        }
    }
}

There's not much to note about the code here, except for the cloning code used to defensively protect immutability, and the tree traversal behavior of printSummary().

The final section of CelestialBody is a static utility delegate class that we can use to calculate the surface gravity. In the old version, this was a simple instance method on the CelestialBody, but the separation of inheritance through enums from behavior through interfaces requires us to move it somewhere else.

/**
 * A static class that is used to simulate the logic that would be
 * implemented in an abstract superclass for Satellite enums, if Java
 * allowed such a thing.
 */
static class Util {

    // private constructor to ensure static-only access
    private Util() {
    }

    /**
     * Calculates and returns the surface gravity of the given {@link
     * CelestialBody}. The result is given in m/s².
     *
     * @param celestialBody the body whose surface gravity is being
     *                      calculated
     * @return the surface gravity, in m/s²
     */
    public static double calcSurfaceGravity(Properties celestialBody) {
        return GRAVITATIONAL_CONSTANT * celestialBody.getMass() / Math.pow(
                celestialBody.getRadius(), 2.0);
    }
}

Overall this version of CelestialBody is definitely unwieldly compared to the old version. However, by rewriting CelestialBody as an interface instead of a class, it can be used as part of the interface for our enum types. The way we will use this is to define other types by implementing this interface, with the properties decoupled to the Properties inner interface. Children enums of this pattern will implement the outer interface, CelestialBody, and delegate all requests for information about logic and relationships to the inner interface, Properties. The advantage of this is that we get all of the power of enums in the main class but flexibility of shared interface and behavior in the inner classes.

Star

Next, let's look at Star. In the initial version, it was just an enum that didn't have any of the properties or logic. Now, we can have that enum implement CelestialBody and use its ImmutableProperties implementation to get the properties, including an array of all of its Planets.

package com.ociweb.sett;

/**
 * An enumeration of the stars at the center of solar systems.
 */
public enum Star implements CelestialBody {
    SOL(1.98892e30, 6.955e8, Planet.values()); // singleton

    private final Properties properties;

    private Star(double mass, double radius, Satellite[] satellites) {
        this.properties = new ImmutableProperties(name(), mass, radius,
                satellites);
    }

    public Properties getProperties() {
        return properties;
    }

}

This implementation allows us to combine three elements that were separated into multiple incompatible places before:

  1. A type-safe enumeration of all the stars (only one in this case). In the previous version, this was the only purpose of com.ociweb.sett.initial.Star.
  2. The physical properties (mass and radius) of each star. In the previous version, these were set in the constructor to com.ociweb.sett.initial.CelestialBody within com.ociweb.sett.initial.SolarSystem
  3. The relationship between a star and its planets. In the previous version, this was set by a mutator on com.ociweb.sett.initial.CelestialBody within com.ociweb.sett.initial.SolarSystem

At this point, we can already see some payoff for the added complexity we saw in com.ociweb.sett.CelestialBody.

Satellite

Next, let's look at the new Satellite, which is the most complicated of the new files, and which shows all parts of this pattern.

Satellite itself is now an interface that extends CelestialBody to add a reference to the parent body (as in the star around which a planet orbits or the planet around with a moon orbits). It contains an immutable Properties inner class of its own that implements the CelestialBody.Properties interface and adds satellite-specific logic.

There's enough code here to need to look at the individual parts one-by-one. First, we'll look at the outer interface, Satellite. This is the interface that is implemented by enums like Planet, EarthMoon, and MarsMoon.

package com.ociweb.sett;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * An interface representing a generic satellite (planet, moon, etc.). This
 * interface is often implemented by {@link Enum} types. In order to simulate
 * the behavior of abstract-class inheritance for those enums, this interface
 * has inner classes and inner interfaces.
 */
public interface Satellite {
    /**
     * @return the representation of all the values of the Satellite
     */
    Properties getProperties();

    /**
     * Returns the parent body for this Satellite (as in the star around which
     * this planet orbits).
     *
     * @return the parent body for this Satellite
     */
    CelestialBody getParentBody();

    < ...snip inner interfaces and classes...>
}

The Satellite interface inherits getProperties() from its parent interface (included here as a reminder but not in the actual code) and adds one more: getParentBody().

getParentBody() allows bidirectional traversal from moon to star. Ideally, we could just add this logic to the Properties, but cannot due to the order of static initialization. We create each Satellite instance in the constructor of the parent (that is, the planets are initialized within the constructor for Sol, Phobos and Deimos are initialized within the constructor for Mars, etc.). This means that Sol is not fully created at the point that Mars is being initialized, and Mars is not fully created at the point that Phobos is being initialized. As a result, we cannot initialize a reference to the parent body when we create our Properties convenience object - the static initialization is simply not ready for that order of operation. Instead, we must postpone discovery of the parent body until after the structure of the solar system has been created. So that forces us to have the method getParentBody() be separate from the Properties in all the Satellite enum instances.

Now let's look at the concrete implementation of CelestialBody.Properties that Satellite has as an inner class. Again, this is an immutable implementation, and it defines all of the information about a Satellite we need to calculate the orbital period, the surface gravity, and print a full report:

/**
 * An immutable representation of the properties of the {@link Satellite}.
 * Immutability is necessary to honor the contract for enums.
 */
static final class ImmutableProperties implements CelestialBody
        .Properties {
    private final Satellite satellite;
    private final double mass;
    private final double radius;
    private final double semiMajorAxis;
    private final String name;
    private final Satellite[] satellites;

    public ImmutableProperties(Satellite satellite, String name,
            double mass, double radius, double semiMajorAxis,
            Satellite... satellites) {
        this.satellite = satellite;
        this.name = name;
        this.mass = mass;
        this.radius = radius;
        this.semiMajorAxis = semiMajorAxis;
        this.satellites = satellites == null ? null : satellites.clone();
    }

    @Override
    public double getMass() {
        return mass;
    }

    @Override
    public double getRadius() {
        return radius;
    }

    @Override
    public Satellite[] getSatellites() {
        return satellites == null ? null : satellites.clone();
    }

    @Override
    public String name() {
        return name;
    }

    private CelestialBody getParentBody() {
        return satellite.getParentBody();
    }

    /**
     * Calculates and returns the orbital period of this {@link Satellite}
     * which orbits the given parent body. The result is given in seconds.
     *
     * @param parentBody the body around which the satellite orbits
     * @return the orbital period, in seconds
     */
    public double getOrbitalPeriod(CelestialBody parentBody) {
        return 2 * Math.PI * Math.sqrt(Math.pow(semiMajorAxis, 3.0) /
                (GRAVITATIONAL_CONSTANT *
                        parentBody.getProperties().getMass()));
    }

    /**
     * Prints a summary of the calculated orbital and physical
     * characteristics of this {@link Satellite} and any of its own
     * satellites.
     */
    @Override
    public void printSummary() {
        System.out.println("Summary for " + getParentage());

        CelestialBody parentBody = getParentBody();
        long orbitalPeriod = (long) getOrbitalPeriod(parentBody);
        System.out.printf("Orbital Period: %1$d hours/%2$d days\n",
                TimeUnit.SECONDS.toHours(orbitalPeriod),
                TimeUnit.SECONDS.toDays(orbitalPeriod));

        System.out.printf("Surface Gravity: %1$e m/s²\n\n",
                CelestialBody.Util.calcSurfaceGravity(this));

        if (satellites != null) {
            for (Satellite child : satellites) {
                child.getProperties().printSummary();
            }
        }
    }

    /**
     * Generates and returns a String listing all the orbital parents of
     * this satellite.
     * <p/>
     * For example, for the Earth's moon, it would return
     * <pre>", satellite of EARTH, satellite of SOL"</pre>.
     *
     * @return a String showing orbital parentage
     */
    private String getParentage() {
        List<CelestialBody> parents = new ArrayList<CelestialBody>();
        CelestialBody parentBody = getParentBody();
        parents.add(parentBody);
        while (parentBody instanceof Satellite) {
            Satellite satelliteParent = (Satellite) parentBody;
            parentBody = satelliteParent.getParentBody();
            parents.add(parentBody);
        }

        StringBuilder sb = new StringBuilder(name());
        for (CelestialBody parent : parents) {
            sb.append(", satellite of ");
            sb.append(parent.getProperties().name());
        }
        sb.append(":");

        return sb.toString();
    }
}

Much of this implementation is very similar to the ImmutableProperties implementation in CelestialBody. However, it also adds the ability to get the parent body (by delegating to the related Satellite object) and to calculate the orbital period from physical properties of the satellite and its parent. It also has a more complicated implementation of printSummary() to support the listing of parent relationship.

Planet

Now that we've completed the heavy lifting of understanding the Satellite interfaces and the inner classes that support it, let's look at Planet to see how it is used:

package com.ociweb.sett;

/**
 * An enumeration of the planets in our solar system. We only show the inner
 * planets, for simplicity.
 */
public enum Planet implements Satellite {
    MERCURY(0.3302e24, 2.4397e6, 57.91e9),
    VENUS(4.869e24, 6.0518e6, 108.21e9),
    EARTH(5.9742e24, 6.3781e6, 149.6e9, EarthMoon.values()),
    MARS(0.64185e24, 3.3962e6, 227.92e9, MarsMoon.values());

    final ImmutableProperties properties;

    private Planet(double mass, double radius, double semiMajorAxis) {
        this(mass, radius, semiMajorAxis, null);
    }

    private Planet(double mass, double radius, double semiMajorAxis,
            Satellite[] satellites) {
        this.properties = new ImmutableProperties(this, name(), mass, radius,
                semiMajorAxis, satellites);
    }

    public ImmutableProperties getProperties() {
        return properties;
    }

    @Override
    public CelestialBody getParentBody() {
        return Star.SOL;
    }

}

Here we see more of the power of this pattern. This enum defines the same four inner planets that the original version of Planet defined. However, now all of the configuration information for each of the planets is here (instead of built manually in the SolarSystem class), and we get the orbital calculation logic that is shared with other Satellites.

For example, Mercury and Venus are defined with their physical properties in their constructors (mass, radius, and semi-major axis). Earth and Mars are similar, except they also load their moons into the constructors (those moons are passed into the ImmutableProperties).

The only methods that need to be implemented here for the Satellite interface are getProperties() (this one method definition replaces four that would be needed otherwise) and getParentBody() (which has a simple implementation since each planet orbits the same parent).

EarthMoon and MarsMoon

Finally, let's look at the enums which share Satellite with Planet as an interface, but themselves represent satellites of planets:

package com.ociweb.sett;

/**
 * An enumeration of the moons that orbit the Earth.
 */
public enum EarthMoon implements Satellite {
    LUNA(0.07349e24, 1.7381e6, 0.3844e9);

    final Properties properties;

    private EarthMoon(double mass, double radius, double semiMajorAxis) {
        this.properties = new ImmutableProperties(this, name(), mass, radius,
                semiMajorAxis);
    }

    public Properties getProperties() {
        return properties;
    }

    @Override
    public CelestialBody getParentBody() {
        return Planet.EARTH.getProperties();
    }

}
package com.ociweb.sett;

/**
 * An enumeration of the moons that orbit Mars.
 */
public enum MarsMoon implements Satellite {
    PHOBOS(1.072e16, 1.11e4, 9.38e6),
    DEIMOS(1.5e15, 6.2e4, 2.346e7);

    final Properties properties;

    private MarsMoon(double mass, double radius, double semiMajorAxis) {
        this.properties = new ImmutableProperties(this, name(), mass, radius,
                semiMajorAxis);
    }

    public Properties getProperties() {
        return properties;
    }

    @Override
    public CelestialBody getParentBody() {
        return Planet.MARS.getProperties();
    }

}

These enums are very similar to Planet, but none of the moons defined here has its own satellite. However, it would be easy to add any such third layer of satellite by extending the pattern.

Finally, to pull this all together, we have the main class:

package com.ociweb.sett;

/**
 * The main class for this example, it prints a summary of the Solar System.
 */
public class SolarSystem {

    public static void main(String[] args) {
        Star.SOL.getProperties().printSummary();
    }
}

This class produces the same printed output as the earlier version, but it is much, much simpler. Instead of defining all the properties and relationships and some of the printing behavior like the early version did, we can now just start with the Sun and let the definitions and logic in all the enums and interfaces do all the work for us.

Summary

With this thorough example, we see how we can use a combination of interfaces and utility classes to simulate having abstract enum implementations. With this pattern, we can share behavior across related enums while maintaining the type-safe restrictions that we get with enums.

It would be nice to have full support for extendible enums in Java, and perhaps that will come in future versions. In the meantime, this pattern might solve problems in your application.

References


Valid XHTML 1.0 Strict [Valid RSS]
RSS
Top