Java为什么静态打印出文本而不是方法 [英] Java why static prints out text first than method

查看:456
本文介绍了Java为什么静态打印出文本而不是方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道为什么静态总是首先打印而不是方法。

Just wondering why static is always the one that will print out first rather than a method.

代码:

public class TestMe {
    static {
        System.out.println("D");
    }

    {
        System.out.println("B");
    }


    public void printMe() {
        System.out.println("Z");
    }

    public static void main(String []args) {
        new TestMe().printMe();
    }

}

输出:

D
B
Z


推荐答案

您的班级中有两种类型的初始化程序块

You have two types of initializer block in your class

一个是静态初始化程序在初始化类时执行

one is static initializer which is executed by the time the class is initialized

8.7。静态初始化程序

A static initializer declared in a class is executed when the class is initialized

8.6。实例初始值设定项

两个是实例初始值设定项,当类的实例已经创建时执行

two is the Instance Initializers which is executed when instance of the class is already create

An instance initializer declared in a class is executed when an instance of the class is created 

这些来自 JLS文档

所以静态初始化程序与已创建该类的实例时调用的实例初始化程序因此静态初始化程序

So static initializer will be called directly when class is initialized vs Instance Initializers that is called when instance of that class is already created thus static initializer is executed first.

这篇关于Java为什么静态打印出文本而不是方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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