public class Test{
public static void main(String args[]){
Test t = new Test();//默認的無參構造函數
}
}
運行結果:
2.如果類提供了構造函數,無論是否有參,Java都不會提供默認的無參構造函數。
public class Test{
public Test(){System.out.println("無參構造函數");}//(1)無參構造函數
public Test(int x){System.out.println("有參構造函數");}//有參構造函數
public static void main(String args[]){
Test t = new Test();//(1)如果被註釋,這行語句就會出錯
Test t2 = new Test(2);
}
}
運行結果:
[color=blue]無參構造函數
有參構造函數[/color]
[color=red]注意:如果類僅僅提供了有參的構造函數,那麼調用無參構造函數就會出錯,無法編譯。[/color]
3.子類構造函數會默認調用父類的無參構造函數
class Base{
public Base(){System.out.println("父類無參構造函數");}
public Base(int x){System.out.println("父類有參構造函數");}
}
public class Test extends Base{
public Test(){System.out.println("子類無參構造函數");}
//public Test(){super();System.out.println("子類無參構造函數");}
public Test(int x){System.out.println("子類有參構造函數");}
public static void main(String args[]){
Test t = new Test();//(1)
Test t2 = new Test(2);//(2)
}
}
運行結果:
[color=blue]父類無參構造函數
子類無參構造函數
父類無參構造函數
子類有參構造函數[/color]
(1)和(2)都會調用Base();
[color=red]注意:如果父類僅僅提供了有參的構造函數,那麼子類的構造函數就會出錯。[/color]
4.子類使用super()關鍵字可以指定調用父類哪個構造函數
class Base{
public Base(int x){System.out.println("父類有參構造函數");}
}
public class Test extends Base{
public Test(){super(2);System.out.println("子類無參構造函數");}
public Test(int x){super(x);System.out.println("子類有參構造函數");}
public static void main(String args[]){
Test t = new Test();//(1)
Test t2 = new Test(2);//(2)
}
}
運行結果:
[color=blue]父類有參構造函數
子類無參構造函數
父類有參構造函數
子類有參構造函數[/color]
(1)和(2)都會調用父類的有參構造函數。
[color=red]注意:super()語句必須是構造函數的第一條語句。[/color]