java複用類學習

來源:互聯網
上載者:User

複用類就是把之前寫好的代碼再次利用、不需要從新編碼,它有二種形式:

第一:使用類而不破壞現有程式碼,這種方法很直觀,只需在新的類中產生現有類的對像,由於新的類是由現有類的對象所組成,所以也叫:組合。

第二:繼承,按照現有類的類型來建立新類。

組合的學習

一:文法,把對象引用置於新類中即可。

例如:

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





















聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.