Static code block in Java, Construction code block, construction method detailed _java

Source: Internet
Author: User

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

Analytical:

1. Static code block: is in the class loading process of the third stage of initialization, the main purpose is to give the class variable to the initial value.

2. Construction code block: is independent, must rely on the carrier to run, Java will put the construction code block in front of each construction method, to instantiate some common instance variables, reduce the amount of code.

3. Construct method: for instantiating variables.


Summary:

1 is class-level, 2, 3 is instance-level, so 1 takes precedence 2, 3.

Their order of execution is 1>2>3;

Above this Java static code block, the construction code block, the construction method detailed explanation is small arranges to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.