Java-4.7 constructor initialization (3)
Next, go to the previous chapter.
(4) initialize static explicit Fields
Some attribute fields are initialized using static code blocks.
package com.ray.testobject;public class Test {private static int id;private static String name;static {id = 0;name = abc;System.out.println(id: + id);System.out.println(name: + name);}public static int getId() {return id;}public static void main(String[] args) {// new Test();System.out.println(Test.getId());}}
If we release new Test (), the following results will be obtained. Because the code block is executed only once.
Output:
Id: 0
Name: abc
0
Here is an example:
package com.ray.testobject;public class Test {private static int id = 0;private static String name;static {System.out.println(id: + id);name = abc;System.out.println(name: + name);}public Test() {System.out.println(create Test);}public static void main(String[] args) {new Test();new Test();}}
Output:
Id: 0
Name: abc
Create Test
Create Test
(5) initialize non-static Domains
package com.ray.testobject;public class Test {private String name;{name = abc;System.out.println(name: + name);}public static void main(String[] args) {new Test();new Test();}}
Output:
Name: abc
Name: abc
Initialize non-static fields. Each new code block is executed once.
Summary: This chapter mainly discusses explicit static domain initialization and non-static domain initialization.
This chapter is here. Thank you.
-----------------------------------