简体   繁体   中英

Methods step by step

I have kind of code. And I want to know why "block b" running first, but not "constructorb". The same thing at Class A. Thanks.

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

    {
        System.out.println("block b");
    }
}

class A extends B {
    A() {
        super();
        System.out.println("constructor a");
    }

    {
        System.out.println("block a");
    }

    public static void main(String[] args) {
        A a = new A();
    }
}
output:
block b
constructorb
block a
constructor a

Instance initializers (ie the {} blocks) are effecitvely, if not literally, folded into the constructor. The same thing happens with field initialization. Both instance initializers and field initializations are inserted just after the super(...) constructor call (whether implicit or explicit) but before the rest of the constructor code. So when you have:

public class Foo {

  private int bar = 5;

  {
    System.out.println("Instance initializer");
  }

  public Foo() {
    System.out.println("Constructor");
  }
}

It's compiled as if the following was written:

public class Foo {

  private int bar;

  public Foo() {
    super();
    this.bar = 5;
    System.out.println("Instance initializer");
    System.out.println("Constructor");
  }
}

The order that fields are initialized and instance initializers are executed is, however, determined by their order in the source code. But note that the placement of the constructor is irrelevant.

This is described in §8.8.7.1 of the Java Language Specification .

It is because block a is in a non-static block. A non-static block executes when the object is created, before the constructor

It is a normal Object instance initialization process.

There are two principles in the process of instance initialization:

  1. the static method would run before constructor method .
  2. the parent class would run before child class .

Now, you have parent class named B , and child class named A extends B. So, the class B should run before class A .

Next. In class B , you define a static method which is

    {
        System.out.println("block b");
    }

So, the string block b is printed first. And then constructor method runs:

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

So, the string constructorb is printed second.

Now, class B runs finish. And then class A runs as the order static mehod first and constructor method second.

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