Static code block construction code block construction method in java

  • 2020-05-07 19:45:38
  • OfStack

runs the following code and observes the result:


package com.test;

public class HelloB extends HelloA {
  
  public HelloB() {
  }

  {
    System.out.println("I'm B class");
  }
  
  static {
    System.out.println("static B");
  }

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

class HelloA {
  
  public HelloA() {
  }

  {
    System.out.println("I'm A class");
  }
  
  static {
    System.out.println("static A");
  }
  
}

results are as follows:


static A
static B
I'm A class
I'm B class

:

1. Static block of code: this is done during the initialization of step 3 of the class loading process, with the primary purpose of assigning initial values to class variables.

2. Construction of code blocks: it is independent and must be attached to the carrier to run. Java will put construction code blocks in front of each construction method to instantiate some common instance variables and reduce the amount of code.

3. Constructor: used to instantiate variables.


Summary:

1 is at the class level, 2 and 3 are at the instance level, so 1 takes precedence over 2 and 3.

They are executed in order of 1 > 2 > 3;


Related articles: