1.普通初始化块
在一个类的声明中可以包括多个代码块,当类构造对象时,这些代码块会被自动执行。
class Person { private int age; private String name; private static int id = 0; {//普通初始化块 System.out.println(id); id++; System.out.println(id); } } public class Main { public static void main(String[] args) { Person s = new Person(); Person s1 = new Person(); } }
运行截图:
2.静态初始化块
其只在系统首次构造对象时执行。
class Person { private int age; private String name; private static int id = 0; static{//静态初始化块 System.out.println(id); id++; System.out.println(id); } } public class Main { public static void main(String[] args) { Person s = new Person(); Person s1 = new Person(); } }
运行截图:
3.初始化块的继承性
当类存在继承关系时,会从上到下,一级一级的执行静态初始化块。
class Person { static{ System.out.println("static init Person"); } { System.out.println("common init Person"); } } class Person1 extends Person{ static{ System.out.println("static init Person1"); } { System.out.println("common init Person1"); } } public class Max { public static void main(String[] args) { Person1 s = new Person1(); System.out.println("123123123123"); Person1 s1 = new Person1(); } }
运行截图:
标签:初始化,System,Person,static,println,id,out From: https://www.cnblogs.com/kandh/p/17803965.html