静态块初始化 [英] Static block initialization

查看:117
本文介绍了静态块初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一段Java代码:

This is a snippet of Java code:

static {        
    ture = 9;       
}
static int ture;
{ // instance block 
    System.out.println(":"+ture+":");           
}

它是如何编译的?初始化后已执行变量'ture'的声明。据我所知,静态块和字段按它们出现的顺序执行。

How is that it compiles at all? Declaration of variable 'ture' has been performed after initialization. As far as I know static blocks and fields have been executed in the order they appear.

现在为什么实例块中的值9已被打印3次?顺便说一下,类的实例已经创建了3次。
这不是作业,我正在学习Java认证。

And now why is that value 9 within instance block has been printed 3 times? By the way, the instance of the class has been created 3 times. That is not a homework, I am learning Java for certification.

推荐答案

关于你的第一个问题,静态块是确实按它们出现的顺序处理,但是在静态块之前首先处理声明。声明作为类的准备的一部分进行处理(JLS§12.3.2),发生在初始化之前(JLS§12.4.2)。出于学习目的,整个JLS§12可能有用,以及JLS§8,特别是§8.6JLS§8.7(感谢您 Ted Hopp 无可争议的,用于调出这些部分。)

Regarding your first question, static blocks are indeed processed in the order in which they appear, but declarations are processed first, before the static blocks are. Declarations are processed as part of the preparation of the class (JLS §12.3.2), which occurs before initialization (JLS §12.4.2). For learning purposes, the entire JLS §12 may be useful, as well as JLS §8, particularly §8.6 and JLS §8.7. (Thank you to Ted Hopp and irreputable for calling out those sections.)

您的引用代码中没有足够的信息来回答您的问题第二个问题。 (无论如何,在SO上最好每个问题提出一个问题。)但是例如:

There isn't enough information in your quoted code to answer your second question. (In any case, on SO it's best to ask one question per question.) But for instance:

public class Foo {
    static {     
        ture = 9;   
    }

    static int ture;

    {   // instance block   
        System.out.println(":"+ture+":");

    }

    public static final void main(String[] args) {
        new Foo();
    }
}

...仅输出 :9: 一次,因为只创建了一个实例。如果你删除 new Foo(); 行,它根本不会输出它。如果您看到:9:三次,那么您将在未显示的代码中创建三个实例。

...only outputs :9: once, because only one instance has been created. It doesn't output it at all if you remove the new Foo(); line. If you're seeing :9: three times, then it would appear that you're creating three instances in code you haven't shown.

这篇关于静态块初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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