Search code examples
javastaticfinal

static and final in java


I was reading about enumeration examples in Java from this page.

In the first example, the only part I did not understand was the use of the static keyword in this part of the code:

private static final List<Card> protoDeck = new ArrayList<Card>();

// Initialize prototype deck
static {
    for (Suit suit : Suit.values())
        for (Rank rank : Rank.values())
            protoDeck.add(new Card(rank, suit));
}

public static ArrayList<Card> newDeck() {
    return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
}

Why is the protoDeck declared static and final? Following that, a static loop is used to initialize the protoDeck. I know about static variables that they retain their values between instances of objects. But this is a singleton class (private constructor), so it cannot be instantiated.

So what is the benefit of doing it as above? what would be the implications if proteDeck is not static and final ?


Solution

  • Technically, this is not a singleton class. (A singleton has one instance, this one has none!)

    It is a factory method for an ArrayList<Card>, and the method newDeck works the same way as a constructor would for a class "CardArrayList". It's not a Java constructor but a factory method, but other than that it serves the same purpose: creating new card decks.

    Using a class CardArrayList and subtyping ArrayList would obviously be an alternative. Try this as an exercise: write such as class so that it serves the same purpose. Try to use a constant (static final) for keeping the initial set of objects. You'll notice that there is little difference between these two, except that this approach clearly says that there is no added functionality, but the result is "nothing but an ArrayList<Card> containing a full deck". Subclassing might imply that there is extra functionality, such as ensuring the deck is not messed with.

    The static final variable contains the prototype that serves as template for new objects.