標籤:
其實這裡說的應用只是利用前面學過的知識綜合起來,類比一個非常簡單的項目——印表機。
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基礎學習之物件導向應用