構(gòu)造函數(shù)是和類同名的函數(shù),沒有返回類型,構(gòu)造函數(shù)不能在普通的程序里面調(diào)用,只有當(dāng)這個類被應(yīng)用new實例化的時候才會被運行。構(gòu)造函數(shù)沒有返回類型,實際上,構(gòu)造函數(shù)返回的就是這個class本身。例如
[code]public class MyClass {
public MyClass() {
this(15);
System.out.println("constructor");
}
public MyClass(String s1) {
this(); //調(diào)用沒有參數(shù)的構(gòu)造函數(shù),從構(gòu)造函數(shù)中調(diào)用構(gòu)造函數(shù)只允許用this(), 而且只允許放在構(gòu)造函數(shù)的第一行
System.out.println(s1);
}
public MyClass(int i) {
System.out.println("finally comes here"+i);
}
public static void main(String[] args) {
//看看調(diào)用不同的構(gòu)造函數(shù)有什么區(qū)別。
MyClass mc = new MyClass();
MyClass mc1 = new MyClass("another test");
}
}[/code]