l overloading與overriding
l overloading與overriding的觀念:
overloading |
名字一樣,給不同的條件(參數,多寡或順序不同即可)做不同的事。譬如上班(){},帶參數”SR”時是在執行”趕工寫程式”,不帶參數時是在執行”摸魚”。注意,回傳值不同不可代表overload,且會造成compiler error。 |
overriding |
名字一樣,且條件(參數及回傳值)也要一模一樣。主要是覆寫掉繼承來的東西。譬如繼承了超認真的做人態度,就一定會變得超認真(預設繼承來是不能選擇的)只要可以做到接觸的比爸媽更多(access modifier要更大)且犯更少的錯(throws exceptions範圍要更小),就懂得用另一種態度來生活。 |
l overloading與overriding的區別:
|
meaning |
Access modifier |
Return
type |
Method
name |
Para list |
Throws
exceptions |
overloading |
reuse the method name |
dont’ care |
dont’ care |
同 |
不同(type, count,order) |
dont’ care |
overriding |
redefine the method |
不小 |
同 |
同 |
同 |
subset |
l overriding需特別注意是否滿足下列條件,否則會compiler error。
n access modifier--不小:
u subclass的access modifier不可比superclass的access modifier小。
n ruturn type、para list--同
u subclass與superclass的return type與para list須相同。
n throws exceptions—subset
u subclass所丟出的checked exception範圍不可超過superclass所丟出的exception。
n final methods不可被overridden。
n final class中的所有methods不會被overridden,因為final class不會有subclass。
n private method不會overridden,因為subclass不會繼承superclass的private members。
n overriding method(subclass)不可以是static method。
n static method不可被non-static method overridden,只可被subclass的static method shadowed override superclass時只有method會被覆寫,property不會被覆寫。
来自:【 Garfield 的 SCJP 閱讀筆記 】
|