Java 中override、overload、overwrite區別,以及與多態的關系


Java 中override、overload、overwrite區別,以及與多態的關系

from:http://blog.csdn.net/lzhang007/article/details/7960950

 

 

分類: java override overload overwrite 961人閱讀 評論(1) 收藏 舉報

一  

overload:重載的意思,這沒啥能混淆的了,就是在同一個類當中,為了增加通用性,寫了很多方法,這些方法只有一個要求,參數的數量和類型不同,但返回值和方法屬性必須相同,否則不屬於重載,

比如:1.public class Parent{

                                                                           public int add(int a, int b){}

                                                                           public int add(int a,float b){}

                                                                           public int add(int a,int b,float c){}

                                                                            以上均屬於overload 

                                                                            protected int add(int a,float b){}

                                                                             public float add(int a,float b){}   }(注意:java中明確聲明在同一個類中兩個方法名字和參數相同而返回值不同是不被允許的)

                                                                 public class Child extends Parent{

                                                                             public int add(int a,float b){}(這種在The Java™ Tutorial Fourth Edition中也稱作overload但是跟superclass中的同名方法是兩種完全不同的方法)

                                                                                                                               }

                                                                              均不屬於overload

參考:http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

提示:Note: Overloaded methods should be used sparingly, as they can make code much less readable.

它不決定java的多態

override有人翻譯是重寫,有人翻譯是覆寫,覆蓋等。其實我認為是一種擴展

因為它是在父類中聲明方法(一般是抽象的),在子類中根據需求去具體定義方法的行為(即modify behavior as needed

它要求override的方法有相同的名字、相同的參數、相同的返回值類型(即the same name, number and type of parameters, and return type

它是一種晚綁定,是決定java多態的一種方式

參考:http://docs.oracle.com/javase/tutorial/java/IandI/override.html

 

overwrite:java中就沒有它的存在,就別以訛傳訛了,java官方文檔沒有該詞的出現,但是國外有人把overwrite解釋為override,

比如:http://stackoverflow.com/questions/837864/java-overloading-vs-overwriting

Overriding, which is what I think you mean by "overwriting" is the act of providing a different implementation of a method inherited from a base type, and is basically the point of polymorphism by inheritance, i.e.

public class Bicycle implements Vehicle {
    public void drive() { ... }
}

public class Motorcycle extends Bicycle {
    public void drive() {
        // Do motorcycle-specific driving here, overriding Bicycle.drive()
        // (we can still call the base method if it's useful to us here)
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM