Talking about static initialization block and non-initialization block in Java

Source: Internet
Author: User

It is well known that there are two types of initialization blocks in the Java programming language: static initialization block non-static initialization blocks What difference do they have? Let's talk about the difference between static initialization block and non-static initialization block in Java static initialization block definition: static{} Execution priority is higher than non-static initialization block, it will be executed once when the object is loaded into the system, execution is destroyed, it can only initialize class variables, that is, static decorated data Members. It will be executed when the class loads. Execution Priority: 1 non-static initialization block definition: {} If there is a static initialization block, execute the static initialization block and then execute the non-static initialization block, which will be executed once each object is generated, it can initialize the instance variables of the class. A non-static initialization block is run when the constructor executes, before the constructor body code executes. Execution Priority: 2 instances:
1  Packagecom. Demo;2  Public classDemo03 {3 String name;4     intAge ;5     //constructor Initialization priority: 36      PublicDemo03 (String name,intAge ) {7          This. name=name;8          This. age=Age ;9System.out.println ("constructor");Ten     } One      A     //non-static initialization priority: 2 -     { -SYSTEM.OUT.PRINTLN ("Non-static initialization"); the     } -     //Static Initialization priority: 1 -     Static{ -SYSTEM.OUT.PRINTLN ("Static Initialization"); +     } -      +      A      Public Static voidMain (string[] args) { atDemo03 demo=NewDemo03 ("Zhangs", 1); -     } -}
Result: static initialization of non-static initialization constructors

Talking about static initialization block and non-initialization block in Java

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.