構(gòu)造函數(shù)
1 public class Demo { 2 private int x; 3 private String string; 4 public Demo(int x) { 5 this.x = x; 6 } 7 public Demo(int x,String string){ 8 this(x); //一個類的構(gòu)造器調(diào)用這個類中的其他構(gòu)造器 9 10 this.string=string; 11 } 12 }
1、構(gòu)造函數(shù)void返回(構(gòu)造函數(shù)可被重載,但不能被重寫)
構(gòu)造函數(shù)的返回類型不可指定,如果你在構(gòu)造函數(shù)前面寫上void ,那么構(gòu)造函數(shù)就變成無效的了,但不會報錯。因為構(gòu)造函數(shù)的作用就是要生成一個類的對象,這個生成的對象的指針要返回給系統(tǒng),如果寫成void,那么構(gòu)造函數(shù)就無任何返回。
eg:
1 class Scope { 2 3 String s="11"; 4 5 void Scope() { //注意此處構(gòu)造函數(shù)添加了void,但不會編譯錯誤,也不會運行錯誤 6 s = "constructor"; 7 } 8 public static void main(String[] args) { //注意此處main函數(shù)聲明必須是public static void,否則運行出錯! 9 Scope m = new Scope(); 10 m.go(); 11 } 12 13 void go() { 14 System.out.println(s); 15 } 16 }
結(jié)果是:

可以看出在構(gòu)造函數(shù)前面寫上void ,那么構(gòu)造函數(shù)就變成無效。
2、構(gòu)造函數(shù)void形參
public class Scope{ public static void main(String[] argv){ System.out.println("two"); Scope a=new Scope(); } Scope(void){ //構(gòu)造函數(shù)參數(shù)void會導(dǎo)致編譯報錯 System.out.println("tq"); } Scope(){ System.out.println("tq1"); } }
this表示是當(dāng)前類對象。類方法是指用static修飾的方法,普通方法叫對象方法。
構(gòu)造方法每次都是構(gòu)造出新的對象,不存在多個線程同時讀寫同一對象中的屬性的問題,所以不需要同步 。
容器保存的是對象的引用
如果父類中的某個方法使用了
synchronized關(guān)鍵字,而子類中也覆蓋了這個方法,默認(rèn)情況下子類中的這個方法并不是同步的,必須顯示的在子類的這個方法中加上
synchronized關(guān)鍵字才可。當(dāng)然,也可以在子類中調(diào)用父類中相應(yīng)的方法,這樣雖然子類中的方法并不是同步的,但子類調(diào)用了父類中的同步方法,也就相當(dāng)子類方法也同步了
浙公網(wǎng)安備 33010602011771號