Java4Android基礎學習之物件導向應用

來源:互聯網
上載者:User

標籤:

  其實這裡說的應用只是利用前面學過的知識綜合起來,類比一個非常簡單的項目——印表機。

1、先是做一個印表機列印,

public class father {    void turn_on(){        System.out.println("turn on");    }    void turn_off(){        System.out.println("turn off");    }    void  print(String s){        System.out.println("print " + s);    }}
public class test {    public static void main(String args []){        father p = new father();        p.turn_on();        p.print("a");        p.turn_off();    }}

這樣很簡單就實現了開機,關機,列印

2、然後是增加了印表機的個數;

  1)這裡就使用繼承,因為如果一個印表機寫一個類的話,那將產生很多重複代碼(不管什麼印表機都有開機,關機,列印這幾個功能);

  2)每個印表機的類裡面寫他特有的方法,若父類中繼承來的方法不滿足要求的話,就在子類中重寫,利用 super來調用父類中的函數;

  如:

//父類public class father {    void turn_on(){        System.out.println("turn on");    }    void turn_off(){        System.out.println("turn off");    }    void  print(String s){        System.out.println("print " + s);    }}
//印表機1public class hpprint extends father{}//印表機2public class canno extends father{    void clean(){        System.out.println("Clean");    }    void turn_off(){        this.clean();        super.turn_on();    }}
//主函數public class test {    public static void main(String args []){        father p = new father();        p.turn_on();        p.print("a");        p.turn_off();    }}

這樣的話就能減少很多重複代碼,試想下,如果有十台印表機的話,就比每個類裡都寫開機,關機這些函數效率要高得多多的了。

 

  這個類比的項目正好把前面學到的知識都聯絡起來了,再次回顧了一篇,加深印象。

Java4Android基礎學習之物件導向應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.