java 中(overload) 重載與(override)覆蓋

來源:互聯網
上載者:User

在Java語言規範中,一個方法的特徵僅包括方法的名字,參數的數目和種類,而不包括方法的傳回型別,參數的名字以及所拋出來的異常。在Java編譯器檢查方法的重載時,會根據這些條件判斷兩個方法是否是重載方法。但在Java編譯器檢查方法的置換時,則會進一步檢查兩個方法(分處超類型和子類型)的返還類型和拋出的異常是否相同。

QUESTION NO: 3
1. class A {
2. protected int method1(int a, int b) { return 0; }
3. }
Which two are valid in a class that extends class A? (Choose two)
A. public int method1(int a, int b) { return 0; }
B. private int method1(int a, int b) { return 0; }
C. private int method1(int a, long b) { return 0; }
D. public short method1(int a, int b) { return 0; }
E. static protected int method1(int a, int b) { return 0; }

310-035中的題目,標準答案是A,C

A是override,access從protected--->public變寬了,因此是正確的。
B,D也是override,B從protected--->private變窄了,D的傳回型別變了,所以都錯誤。
C是overload,access的寬窄和傳回型別都無所謂,所以是正確的。
E是override,但是增加了static,因為static method cannot hide the instance method from super class.因此是錯誤的。
所以選AC。
子類繼承父類並且覆蓋父類方法的叫override  --重寫,覆寫,覆蓋
子類有多個相同方法名稱,但是參數不同,叫overload  - 重(zhong)載,過載

重載是:
當多個方法具有相同的名字而含有不同的參數時產生
那麼對參數不同的調用,實際調用不同的方法
也可以理解為實際上有兩個方法,名字同,參數不同!


覆蓋(OVERWRITE)注意

不能降低原方法的"可見度

傳回型別不同都不能構成方法的覆蓋

重載(OVERLOAD)注意
只有參數不同才能構成重載

聯繫我們

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