Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual "static" method declaration

Tags:

java

public class Card {

    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
        SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    private final Rank rank;
    private final Suit suit;
    private Card(Rank rank, Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public Rank rank() { return rank; }
    public Suit suit() { return suit; }
    public String toString() { return rank + " of " + suit; }

    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
    }
}

I have a quick question. The code block that starts right after the static keyword declaration, what type of method is that ? I haven't ever seen that before. If anyone could enlighten me, that would be greatly appreciated. Thanks.

like image 321
Jack Avatar asked May 25 '10 07:05

Jack


2 Answers

This is not a method, but a static Initializer block of a class. You can read more about it in the Java Language Specification.

The code within is executed once after loading the class.

like image 137
Grzegorz Oledzki Avatar answered Sep 28 '22 08:09

Grzegorz Oledzki


As Grzegorz correctly points out, it's a static initializer block.

Here is another resource explaining the difference between class initialization and instantiation, as well as the order in which class variables and static initializer blocks are called.

A related concept is that of instance initializer blocks, which can be used together with anonymous classes for the handy double-brace initialization idiom:

private static final Set<String> VALID_CODES = new HashSet<String>() {{
    add("XZ13s");
    add("AB21/X");
    add("YYLEX");
    add("AR2D");
}};
like image 40
Yang Meyer Avatar answered Sep 28 '22 07:09

Yang Meyer