Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

11.1 Enums — constants with data

Lesson

Attaching values to constants

An enum can be more than a bare list: each constant can carry data. Give the enum a field, a constructor, and give arguments in parentheses after each constant. The enum can then have ordinary methods, like a getter. This lets a constant bundle a name together with related information.


Worked example

enum Planet {
    EARTH(9.8), MARS(3.7);   // each constant passes a value to the constructor
    private double gravity;
    Planet(double gravity) { this.gravity = gravity; }
    public double getGravity() { return gravity; }
}

System.out.println(Planet.EARTH.getGravity());   // 9.8
System.out.println(Planet.MARS.getGravity());    // 3.7

The constructor runs once per constant, storing that constant's data.


▶ Try it: run this — each planet carries its own gravity value.



To give each enum constant its own data, you add...


In EARTH(9.8), the 9.8 is...


Type exactly what this program prints.

enum Coin {
    DIME(10), QUARTER(25);
    private int cents;
    Coin(int c) { cents = c; }
    public int getCents() { return cents; }
}
public class Main { public static void main(String[] a){
    System.out.println(Coin.DIME.getCents());
    System.out.println(Coin.QUARTER.getCents());
}}

The enum constructor runs...


True or false?