The difference between the static structure and code block code block

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/CronousGT/article/details/78390933
Package gt;

/ **
* the Created by Cronous ON 2017/10/29.
* difference between static block of code and configuration of the code block
* /
public class day01 {

static void main public (String [] args) {
the Person P1 = the Person new new ( "Tom");
the Person P2 = the Person new new ( "Jerry");
p1.sayHello ();
p2.sayHello ();
}
}

class the Person {
String name Private;
static int I = 2; // static variables
the Person () {}
the Person (String name) {
this.name = name;
}
// static block
static {
System.out.println ( "come!" );
// here we perform a class initialization operation, such as modifying the value of the static variable
I = I + 1;
}
void the sayHello public () {
System.out.println ( "name =" + name + ", I =" + I);
}
}
console output is as follows:

I came in!
= Tom name, I =. 3
name = Jerry, I =. 3

We can understand that the output of the console, block static part of the role of the class, it is only executed once for initialization class, here we use the example of static variables do, we initialize the

Initializes the value of i is 3, the value of all objects created after i are the same.

 

Let us look at the code block structure

gt Package;

/ **
* the Created by 2017/10/29 Cronous ON.
distinction * static block of code and configuration of the code block
* /
public class day01 {

public static void main (String [] args) {
the Person new new the Person P1 = ( "Tom");
the Person P2 = the Person new new ( "Jerry");
//p1.sayHello ();
//p2.sayHello ();
}
}

class the Person {
Private String name;
the Person () {}
the Person (String name ) {
this.name = name;
}
// code block configured
{
Cry ();
}
public void Cry () {
System.out.println ( "yapping !!!" + name);
}
public void the sayHello () {
System.out.println ( "name =" name +);
}
}
Here we see that we will p1.sayHello () and p2.sayHello () all commented out and found the console is printed as follows:
yapping! ! ! null
yapping! ! ! null

Each object description will first call the initialization code block content configured for initialization of the object, and can be described by the name = null block content is configured to preferentially execute the constructor.

Summarized as follows:

Acting on the static block of code, mainly for one class initialization operation and performs only once;

Code block is configured to act on the object, the object is mainly used for the initializing operation, it will be executed as long as the object is created, due to the configuration and the priority function;

Guess you like

Origin www.cnblogs.com/mark5/p/11069644.html