定義Person類函數
package models; public class Person { public Person() { System.out.println("person constructor"); } { System.out.println("person init block"); } static { System.out.println("person static block"); } }
定義Chinese類spa
package models; public class Chinese extends Person { public Chinese() { // super(); System.out.println("chinese constructor"); } { System.out.println("chinese init block"); } { System.out.println("chinese init block2"); } static { System.out.println("chinese static block"); } static { System.out.println("chinese static block 2"); } }
建立Chinese類實例code
public class Program { public static void main(String[] args) { new Chinese(); } }
輸出結果以下:對象
person static block
chinese static block
chinese static block 2
person init block
person constructor
chinese init block
chinese init block2
chinese constructor
執行順序爲:blog
基類靜態初始化塊——當前類靜態初始化塊——基類初始化塊——基類構造函數——當前類初始化塊——當前類構造函數string
it
try { Class.forName("models.Chinese"); } catch (ClassNotFoundException e) { e.printStackTrace(); }
執行結果以下:io
person static block
chinese static block
chinese static block 2
與JAVA相比,.NET中沒有初始化塊及靜態初始化塊class
定義類型以下:emoji
class Person { public Person() { Console.WriteLine("person constructor"); } static Person() { Console.WriteLine("person static constructor"); } } class Chinese : Person { public Chinese() { Console.WriteLine("chinese constructor"); } static Chinese() { Console.WriteLine("chinese static constructor"); } }
建立對象:
class Program { static void Main(string[] args) { new Chinese(); } }
輸出結果以下:
chinese static constructor
person static constructor
person constructor
chinese constructor
執行順序爲:
當前類靜態構造函數——基類靜態構造函數——基類構造函數——當前類構造函數
JAVA與.NET建立對象時都是先執行靜態代碼塊後執行非靜態代碼塊;
JAVA先執行基類中的靜態及非靜態代碼塊;
.NET先執行當前類中的靜態代碼塊,而後先執行基類中的實例構造函數;