預設構造器
預設構造器(又名“無參”構造器)是沒有形式參數的—它的作用是建立一個預設對象。如果你寫的類中沒有構造器,則編譯器會自動幫你建立一個預設構造器。
class Test03{}
class Test04{
public static void main(String[] args) {
Test03 test03 = new Test03();
}
}
複制
new Test03()
建立了一個新對象,并調用預設構造器-即使你沒有明确定義它。
但是如果已經定義了一個構造器(無論是否有參數),編譯器就不會幫你自動建立預設構造器
class Test03{
Test03(int i){}
Test03(double d){}
}
class Test04{
public static void main(String[] args) {
// Test03 test01 = new Test03(); // 編譯器會報錯
Test03 test02 = new Test03(1);
Test03 test03 = new Test03(1.0);
}
}
複制