java中的重寫和重載

來源:互聯網
上載者:User

標籤:anim   static   print   總結   java   變數   style   比較   沒有   

  • 重寫

  在java中有很多的繼承,繼承下來的有變數、方法。在有一些子類要實現的方法中,方法名、傳的參數、傳回值跟父類中的方法一樣,但具體實現又跟父類的不一樣,這時候我們就需要重寫父類的方法,就比如我們有一個類叫做Animals,Animals類中有一個叫做Call,然後我們繼承Animals又產生了Cat類和Dog類,Cat和Dog也分別有自己特別的叫聲,程式如下:

 1 class Animals { 2     public void call() { 3         System.out.println("啊啊啊啊啊啊啊"); 4     } 5 } 6  7  8 public class Cat extends Animals { 9     @Override10     public void call() {11         12         System.out.println("喵喵喵喵喵");13     }14 }15 16 17 public class Dog extends Animals {18 19     @Override20     public void call() {21         System.out.println("汪汪汪汪汪汪");22     }23     24     public static void main(String[] args) {25         Animals animals = new Animals();26         animals.call();27         28         Cat cat = new Cat();29         cat.call();30 31         Dog dog = new Dog();32         dog.call();33     }34 35 }

列印結果如下:

 

  • 重載

  重載是在一個類中實現的,有多個同名方法,但參數不一樣,包括參數類型、參數個數、還可以沒有參數,總之每個重載的方法的參數必須不一樣。

現在我寫一個小程式,用來進行比較兩個數值大小的,代碼塊如下:

 1 public class Compare { 2  3     public void max(int a, int b) { 4         System.out.println(a>b?a:b); 5     } 6      7     public void max(float a, float b) { 8         System.out.println(a>b?a:b); 9     }10     11     12     public void max() {13         /**14          * 無參重載15          * */16         System.out.println("Coding...");17     }18     public static void main(String[] args) {19         // TODO Auto-generated method stub20         Compare compare = new Compare();21         compare.max(102, 23);22         compare.max(2.0f, 3.0f);23         compare.max();24     }25 26 }

列印結果如:

  • 總結

  重寫是外殼不變,核心變。也就是說方法名不變,參數不變,具體實現可以改變。一般是在父類中聲明方法,在子類中重寫。

  重載是方法名不變,但參數一定要變。而且重載的方法一般都寫在一個類中。用一張圖來表示區別如下:

 

java中的重寫和重載

聯繫我們

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