[java] public class Person { public Person() { System.out.println("this is a constructor!"); } static //this is programming first! { System.out.println("this is static code in constructor!"); } } public class StatMain { static { System.out.println("this is a static code in main !"); } public static void main(String args[]) { System.out.println("the program is beginning !"); new Person(); new Person(); } }
public class Person { public Person() { System.out.println("this is a constructor!"); } static //this is programming first! { System.out.println("this is static code in constructor!"); } }
public class StatMain { static { System.out.println("this is a static code in main !"); } public static void main(String args[]) { System.out.println("the program is beginning !"); new Person(); new Person(); } } 运行结果:
this is a static code in main ! //main中的static代码首先执行。
the program is beginning ! //main函数中的程序开始执行。
this is static code in constructor!//类中的static代码开始执行,且只执行一次。
this is a constructor! //类中的程序开始执行。
this is a constructor! //第二次调用只执行除static代码的程序。
|