括号内的说明只有静态关键字作为标题

时间:2015-09-27 19:39:16

标签: java static

我试图找到关于这种特异性的答案但却找不到任何答案。

我在下面的代码中有一个括号内的指令,只有static关键字作为标题。

我确实清楚地了解它的作用,可以像其他任何static方法/变量一样猜测它们的使用,但我不能在其上加上名称。

它不是变量,也不是方法(它不会返回任何内容,甚至不返回“void”),因为使用了static关键字,它肯定不是构造函数。

我们称这种特殊的“方法”是什么?

以下是代码:

    public class Test{

    static {
        System.out.println("What do we call this?");
    }

    public Test(){
        System.out.println("Instance of Test created");
    }

    public static void main(String[] args) {
        new TestSon().go();
    }

    public void go(){
        System.out.println("Go method Test");
    }

}

class TestSon extends Test{

    static {
        System.out.println("Same here...");
    }

    public TestSon(){
        System.out.println("Instance of TestSon created");
    }

    @Override
    public void go() {
        System.out.println("Go method son");
    }
}

输出:

What do we call this?
Same here...
Instance of Test created
Instance of TestSon created
Go method son

2 个答案:

答案 0 :(得分:3)

这是一个所谓的静态初始化块'您可以在https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

了解更多相关信息

答案 1 :(得分:1)

它被称为初始化块,它可以是静态的(每个类一次),也可以是每个对象实例的初始化。

典型用法:

public A {

    static final Map<String, String> TRANSLATIONS = new HashMap<>();
    static {
        TRANSLATUIBS.put("un", "one");
        TRANSLATUIBS.put("deux", "two");
        TRANSLATUIBS.put("trois", "three");
    }

    final URL MY_HOME_PAGE;
    {
         try {
             MY_HOME_PAGE = new URL("...");
         } catch (MalformedURLException e) {
             throw new IllegalStateException();
         ]
    }

对于非静态初始化程序,代码已放在构造函数中。

在第一次使用类时调用静态初始值设定项。因此,如果不使用该类,则不一定要调用它。