3
\$\begingroup\$

I'm working my way through The Java Programming Language, Fourth Edition - The Java Series. This is Exercise 6.4:

Expand your traffic light color enum from Exercise 6.1 on page 152 so that each enum constant has a suitable Color object that can be retrieved with getColor.

The enum from Exercise 6.1 is as follows:

enum TrafficLightColor {
    GREEN,
    RED,
    YELLOW,
}

Is the following an adequate solution?

enum TrafficLightColor {
    GREEN(0, 255, 0),
    YELLOW(255, 255, 0),
    RED(255, 0, 0);

    Color color;

    TrafficLightColor (int r, int g, int b) {
        color = new Color(r, g, b);
    }

    Color getColor() {
        return color;
    }
}

public class Color {
    private int r;
    private int g;
    private int b;

    Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    public int getR() {
        return r;
    }

    public int getG() {
        return g;
    }

    public int getB() {
        return b;
    }
}

public class TrafficLight {
    private TrafficLightColor currentColor;

    TrafficLight(TrafficLightColor currentColor) {
        this.currentColor = currentColor;
    }

    TrafficLightColor getCurrentColor() {
        return currentColor;
    }
}

import org.junit.Test;
import static org.junit.Assert.*;

public class TrafficLightTest {
    @Test
    public void testGetCurrentColor() throws Exception {
        TrafficLight light = new TrafficLight(TrafficLightColor.GREEN);
        assertEquals(0, light.getCurrentColor().getColor().getR());
        assertEquals(255, light.getCurrentColor().getColor().getG());
        assertEquals(0, light.getCurrentColor().getColor().getB());

    }
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Certainly, that seems adequate. You may want to make the color field private, though. Otherwise having a getter is pretty irrelevant. Also, I would make the field final so that the associated color can never be modified.

Were you told to code your own Color class? There's already one provided for you in java.awt.

\$\endgroup\$
2
  • \$\begingroup\$ Good catch Jeff. I've updated the color field to be: private final Color color; Is it good form to update the original post with the correction, or leave as is? The exercise was vague on which Color class to use, but I will have a look at java.awt. Thanks for the feedback. \$\endgroup\$
    – weare138
    Commented Sep 28, 2013 at 23:09
  • \$\begingroup\$ @weare138 I think you're supposed to leave it as is? But who knows. And no problem! \$\endgroup\$
    – asteri
    Commented Sep 28, 2013 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.