Home  >  Article  >  Java  >  Detailed explanation of static code blocks, construction code blocks, and construction methods in Java

Detailed explanation of static code blocks, construction code blocks, and construction methods in Java

高洛峰
高洛峰Original
2017-01-18 15:05:341216browse

Run the following code and observe the results:

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");
  }
   
}

The results are as follows:

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

Analysis:

1. Static code block: It is performed during the initialization of the third step of the class loading process. The main purpose is to assign initial values ​​to class variables.

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

3. Constructor method: used to instantiate variables.


Summary:

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

Their execution order is 1>2>3;

The above in this java The detailed explanation of static code blocks, construction code blocks, and construction methods is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more detailed explanations of static code blocks, construction code blocks, and construction methods in Java, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn