package classloader; public class ClassLoaderDisplayDemo { public static void main(String[] args) { Person person = new Person(); person.process(); } } class Person { static { no = 5;//只能对后面的静态变量no赋值,不能进行其它操作 } private static int no;//如果对no进行赋值操作,则上面static块中对no的赋值操作的结果会被此次的操作覆盖 private String name = getClass().getName(); { System.out.println("Block:" + name); System.out.println("Block:no-->" + no); no = no + 1; System.out.println("Block:no-->" + no); } static { no = no + 1; System.out.println("no:" + no); } public Person(String name) { this.name = name; } public Person() { System.out.println("Name:" + name); } public void process() { System.out.println("process-->Name:" + name); } }
Output:
no:6 Block:classloader.Person Block:no-->6 Block:no-->7 Name:classloader.Person process-->Name:classloader.Person