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

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

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

 

 

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

一   java

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

好比:1.public class Parent{less

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

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

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

                                                                            以上均屬於overload .net

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

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

                                                                 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)
    }
}
相關文章
相關標籤/搜索