資料庫基礎作業:資料庫查詢及約束【練習】
阿新 • • 發佈:2020-12-07
雙親委派
前提:類的生命週期:類的載入->連線(驗證,準備,解析)->初始化->使用->類的解除安裝
class MyObject{ static int num1 = 100; static int num2 = 100;//在類的連線狀態時 會先給num2 賦值0,然後在賦值階段給賦值為100 public MyObject() { num1 = 200; num2 = 200; //在建立物件的時候會給賦值為200 } static MyObject object = new MyObject(); publicstatic MyObject getInstance() { return object; } @Override public String toString() { // TODO Auto-generated method stub return "num1:"+this.num1+"\r\n"+"num2:"+num2; } } public class TestLoader { public static void main(String[] args) { MyObject object= MyObject.getInstance(); System.out.println(object.toString()); } }
結果:
num1:200
num2:200
如果把num2的靜態賦值的位置進行改變:
class MyObject{ static int num1 = 100; //static int num2 = 100;//在類的連線狀態時 會先給num2 賦預設值為0,然後在賦值階段給賦值為100 public MyObject() { num1 = 200; num2 = 200; //在建立物件的時候會給賦值為200} static MyObject object = new MyObject(); static int num2 = 100; public static MyObject getInstance() { return object; } @Override public String toString() { // TODO Auto-generated method stub return "num1:"+this.num1+"\r\n"+"num2:"+num2; } } public class TestLoader { public static void main(String[] args) { MyObject object = MyObject.getInstance(); System.out.println(object.toString()); } }
結果:
num1:200
num2:100
雙親委派:雙親是指:1.JVM自帶的載入器(在JVM的內部所包含,C++) 2.使用者自定義的載入器(獨立於JVM之外的載入器,Java)