Yunpeng Lee
Yunpeng Lee

Reputation: 595

During field initialization, why "this" is not null and all methods can be called?What does "this" refer to?

My code is like this:

public class HelloWorld{

  {
    System.out.println("field init " + this.getName());  
  }

  private String name = null;
  private InnerClass inner = new InnerClass(this);

  private String getName() {
    return name;
  }

  public HelloWorld() {
    name = "hello world";
    System.out.println("class init");
  }

  private class InnerClass {

    public InnerClass(HelloWorld hello) {
      System.out.println((hello == null));
    }
  }

     public static void main(String []args){
       HelloWorld hello = new HelloWorld();
       System.out.println("Hello World.");
     }
}

As far as I know, field initialization is before constructor, so why "this.getName()" can be called and "this == null" is false?

Upvotes: 1

Views: 88

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074969

There'd be little point to calling an instance initializer block if the instance hadn't been created yet, as the purpose of an instance initializer block is to initialize (set the initial information for) the instance (this).

So the JVM creates the instance with all fields set to the "all bits off" default, sets this to refer to that instance, then does any instance initialization you've specified.

More in JLS§12.5: Creation of New Class Instances and JVMS§4.10.2.4.


Side note:

As far as I know, field initialization is before constructor

In effect, yes; the Java compiler prepends instance initialization code to the beginning of every constructor you specify.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234785

Remember that all classes in Java have java.lang.Object as their (ultimate) base class. Before you get to any field initialisation or construction in your class, the this pointer for that base class has already been set up.

Hence, it can never be null.

Upvotes: 0

Related Questions