Just as you were thinking you were finally at the end of the Classes And Objects tutorial, along comes Enums!

  • Use enum types to represent a fixed set of constants.
  • The enum declaration defines a class which implicitly extends java.lang.Enum
  • The class includes a static values method that returns an array of all values.

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6), // parameters for enum constructor
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   
    private final double radius; 

    // enum constructor
    // You can't call this
    Planet(double mass, double radius) { 
        this.mass = mass;
        this.radius = radius;
    }

Questions

  1. True or false: an Enum type can be a subclass of java.lang.String. False, because enum implicitly extends java.lang.Enum and a class can only have one parent.

Exercises

  1. Rewrite the class Card from the exercise in Questions and Exercises: Classes so that it represents the rank and suit of a card with enum types.
    enum Suit {
        Clubs, Hearts, Spades, Diamonds;
    }
    
    enum Rank {
        One, Two, Three, Four, Five, Six, Seven, Eight,Nine,
        Ten,Jack,Queen,King,Ace;
    }
    
        public Card (Rank rank, Suit suit) {
            this.rank = rank;
            this.suit = suit;        
        }
    
  2. Rewrite the Deck class.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s