複用類就是把之前寫好的代碼再次利用、不需要從新編碼,它有二種形式:
第一:使用類而不破壞現有程式碼,這種方法很直觀,只需在新的類中產生現有類的對像,由於新的類是由現有類的對象所組成,所以也叫:組合。
第二:繼承,按照現有類的類型來建立新類。
組合的學習
一:文法,把對象引用置於新類中即可。
例如:
package tst;class WaterSource {private String s;WaterSource(){System.out.println("WaterSource()");s = "Constructed";}public String toString(){return s;}}public class ZhuheTest {private String value1,value2,value3,value4;private WaterSource source = new WaterSource();private int i;private float f;public String toString(){return "value1 = " + value1 + " " +"value2 = " + value2 + " " +"value3 = " + value3 + " " +"value4 = " + value4 + " " +"i = " + i + " " + "f = " + f + "\n" +"source = "+ source;}public static void main(String[] args) {ZhuheTest test = new ZhuheTest();System.out.println(test);}}
1:在定義對象的地方。總是能夠在構造器被調用之前被初始化。
2:在類的構造器中。
3:就在正要使用這些對象之前,這種方式稱為惰性初始化。
4:使用執行個體初始化。
以下是這四種方式的樣本:
package tst;class Soap {private String s;Soap(){System.out.println("Soap()");s = "Constructed";}public String toString(){return s;}}public class Composition {private String s1="happy",s2="Happy",s3,s4;private Soap castille;private int i;private float toy;public Composition(){System.out.println("Inside Bsath()");s3 = "joy";toy = 3.14f;castille = new Soap();}{i = 47;}public String toString() {if(s4 == null)s4 = "joy";return"s1 = " +s1 + "\n" +"s2 = " +s2 + "\n" +"s3 = " +s3 + "\n" +"s4 = " +s4 + "\n" +"i = " + i + "\n" + "toy = "+ toy +"\n" +"castille = "+ castille;}public static void main(String[] args) {Composition test = new Composition();System.out.println(test);}}
以上是對組合的一種學習和初始化的學習總結;
繼承學習
- 繼承是所有oop語言和java語言不可缺少的部分,在建立一個類沒有指定繼承那個類的時候,一般都繼承於:Object。
- 初始化基類:在構造器中調用基類構造器來執行初始化,而基類構造器具有執行基類初始化所需要的所有知識和能力。
package tst;class Art {Art(){System.out.println("Art constructor");}}class Drawing extends Art {Drawing(){System.out.println("Drawing constructor");}}public class Cartoon extends Drawing{public Cartoon(){System.out.println("Cartoon constructor");}public static void main(String[] args) {Cartoon x = new Cartoon();}}
輸出結果:Art constructor
Drawing constructor
Cartoon constructor