Initialization block __java in Java

Source: Internet
Author: User

In Java, there are two types of initialization blocks: static initialization blocks and non-static initialization blocks.

Static initialization block: Use the static definition to execute once when a class is loaded into the system. If you want to initialize a variable in a static initialization block, you can only initialize the class variable, which is the static-decorated data member.
non-static initialization block: Each object is executed once when it is generated, and the instance variables of the class can be initialized.

Non-static initialization blocks are run when the constructor executes and before the constructor body code executes.

The parentheses are the initialization blocks, which are executed when the Java object is created and executed before the constructor.

In fact, the initialization block is the complement of the constructor, initialization block can not receive any parameters , the definition of a number of objects in common with the properties, methods, and so on to initialize the block initialization.

The benefit is to improve the reuse of the initialization block and improve the maintainability of the entire application. --"Crazy Java Handout"

1 package Com.tiandinet.studyjava;
2 
3 public class Testinitiateblock {
4 
5 {
6 System.out.println ("In non-static initialization block!");
7};
8 
9 Static {
System.out.println ("In Static initialization block!");
one}; 
Testinitiateblock () {
System.out.println ("in constructor1!");
The public 
Void Show () {System.out.println ("in Show
()!"); 
/**
@param args * * Public
static void Main (string[] args) {
Testini Tiateblock ti = new Testinitiateblock ();
Ti.show (); 
29}


Run Result:
In static initialization block!
In non-static initialization block!
In constructor1!
In Show ()!

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.