Static code block, construction code block, construction method, static code Construction Method

Source: Internet
Author: User

Static code block, construction code block, construction method, static code Construction Method

 

 

Run the following code and observe 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 ");}}

The result is as follows:

Static Astatic BI'm A classi' m B class

 

 

Resolution:

1. Static code block: it is initiated in step 3 of the class loading process. The main purpose is to grant the class variable an initial value.

2. Construct a code block: it is independent and must be attached to a carrier for running. Java puts the constructed code block in front of each constructor to instantiate some common instance variables and reduce the amount of code.

3. constructor: Used to instantiate a variable.

 

Summary:

1 is a class level, and 2 and 3 are instance-level. Therefore, 1 must take precedence over 2 and 3.

The execution sequence is 1> 2> 3;

 

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.