简体   繁体   中英

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. (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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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