2015-10-17 22 views
2

我已經從我們的導師和書籍中學習到polymorphism意味着有很多shapes,在java中它通過兩種方式實現。確實重載不在多態下?

  • overloading
  • overriding

在oracle docs polymorphism中定義得非常好。但我不明白爲什麼他們沒有定義重載下的多態性,他們只討論重寫?我想通過這種方式許多形狀重載也應該在多態之下。

我已經經歷了所有的問題,但我不清楚這些答案,因爲每個人都沒有提及他們的意見,每個人都有不同的看法,有人說是的,其他人都說沒有理由。

Java The Complete reference 8th ed

我想突出部分(從Java The Complete reference 8th ed引用)寫入示例的overloading。 那麼人人都說超載與ovrloading沒有任何關係,但是壓倒一切?

that how polymorphism is not achieved by overloading? 
+1

檢查http://stackoverflow.com/questions/12893907/is-polymorphism-overloading-and-overriding-are-same-concepts – sam

+0

重載與多態性無關。 – plalx

+0

comon @all誰標記它重複,我不滿意答案,這就是爲什麼我在這裏問它。 –

回答

0

「重載」是用於在同一類具有方法的多個變體的術語。例如:

public class Foo 
{ 
    public String doStuff() 
    { return this.doStuff("stuff") ; } 

    public String doStuff(String sStuff) 
    { return this.doStuff(sStuff, "things") ; } 

    public String doStuff(String sStuff, String sWith) 
    { return "Do " + sStuff + " with " + sWith + "." ; } 
} 

Foo類提供doStuff()方法的三種變體:一個不帶參數,一個具有一個參數,以及一個帶有兩個參數。重載看起來很常見,這種方法的大多數變體實際上只是用一些默認值調用下一個更高複雜度的方法。

這可以讓你有任何的零個,一個或兩個參數可預測的行爲:

Foo foo = new Foo() ; 
System.out.println(foo.doStuff()) ;     // "Do stuff with things." 
System.out.println(foo.doStuff("stuff")) ;   // "Do stuff with things." 
System.out.println(foo.doStuff("more stuff")) ;  // "Do more stuff with things." 
System.out.println(foo.doStuff("stuff", "things")) ; // "Do stuff with things." 
System.out.println(foo.doStuff("things", "stuff")) ; // "Do things with stuff." 

相比之下,「壓倒一切」是多態的原則,在子類中改變的行爲方法從超類。

public class Bar extends Foo 
{ 
    @Override 
    public String doStuff(String sStuff) 
    { return this.doStuff(sStuff, "thingamabobs") ; } 
} 
+0

@OAD另外,爲了比較起見,PHP與Java不同,不允許重載,但它確實允許默認的參數值,它可以給你類似的行爲。 – zerobandwidth

+0

你不應該像'{/ * stuff * /}'一樣寫你的代碼。這是很難閱讀,不值得你用這個保存的幾行。 – Tom

+0

@zerobandwidth查看問題 –

0

多態性是一個非常普遍的術語,它可以在Java中以多種方式實現,並且可以由很少或很多的組件組成。

您提供的鏈接列出了多態性,作爲繼承的一個方面在Java中。儘管overloading屬於多態性概念,但overriding在通過Java中的繼承實現多態性方面更加相關。