Unusual “static” method declaration

后端 未结 3 1968
感动是毒
感动是毒 2021-01-18 14:17
public class Card {

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

    public enum Suit { CLUBS, D         


        
相关标签:
3条回答
  • 2021-01-18 14:49

    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");
    }};
    
    0 讨论(0)
  • 2021-01-18 14:57

    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.

    0 讨论(0)
  • 2021-01-18 15:09

    It is also good to know initialization order, as I remember first in this order comes static variables, than static block. Also important point is time when this static block executes - at the first mention of corresponding class, not at the class instance creation.

    0 讨论(0)
提交回复
热议问题