不寻常的“静态”方法声明 [英] Unusual "static" method declaration

查看:105
本文介绍了不寻常的“静态”方法声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

推荐答案

这不是方法,而是类的静态初始化程序块。您可以在 Java语言规范<中阅读更多相关信息。 / a>。

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.

这篇关于不寻常的“静态”方法声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆