简体   繁体   English

全局变量和构造函数(Java)

[英]Global variables and constructor(Java)

When are variables at the top of the class initialized in comparison to the constructor? 与构造函数相比,什么时候初始化类顶部的变量?

Sorry, this is what I meant: 抱歉,这就是我的意思:

public class aClass {

    private int num;

    public aClass {...}

Default values ( null for object fields, 0 etc. for primitive fields`) are technically never explicitly assigned as far as the emitted bytecode is concerned. 就所发出的字节码而言,从技术上讲,默认值(对象字段为null ,原始字段为0等)从不明确指定。 (This is done "internally" during object instantiation, before any initializer/constructor code runs.) (这在对象实例化期间“内部”完成,然后运行任何初始化程序/构造函数代码。)

Explicit initializer code for instance fields is "copied" at the start of every constructor, after a superclass constructor call (if there is any) in the class by the compiler. 在编译器对类进行超类构造函数调用(如果有) 之后 ,将每个构造函数的开头“复制”实例字段的显式初始化程序代码。 The code sample: 代码示例:

class Foo {
    int bar = 123;

    public Foo() {
        // ...
    }

    public Foo(int bar) {
        this.bar = bar;
        // ...
    }
}

is compiled into bytecode equivalent to: 被编译成等效于以下内容的字节码:

class Foo {
    int bar;

    public Foo() {
        this.bar = 123;
        // ...
    }

    public Foo(int bar) {
        this.bar = 123;

        this.bar = bar;
        // ...
    }
}

Same goes for initializer blocks. 初始化程序块也是如此。 This means these variables get initialised before any normal constructor code executes. 这意味着执行任何常规构造函数代码之前,将初始化这些变量。

Members defined with values are initialized in the constructor, just like any other members. 像其他成员一样,使用值定义的成员在构造函数中初始化。 But it's not exactly the constructor you wrote; 但这不完全是您编写的构造函数。 Java changes each constructor behind the scenes by inserting member initializers and initializer blocks in the beginning of it. Java通过在其开头插入成员初始值设定项和初始值设定项块来更改幕后的每个构造函数。 You could view it as the members getting initialized just before the constructor, if you want to view it temporally. 如果要临时查看它,则可以将其视为在构造函数之前初始化的成员。

Effectively, you can consider them initialized before your constructor gets called. 实际上,您可以考虑在调用构造函数之前对它们进行了初始化。 So if you have: 因此,如果您有:

class Dog {
   private String voice = "woof";

   public Dog() {
      System.out.println(voice); 
   }

}

You'll get "woof" printed to the console successfully, rather than null . 您将成功将“ woof”打印到控制台,而不是null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM