我們可以在 Java 中覆蓋時更改方法簽名嗎?
否,覆蓋父類的某個方法時,我們要確保兩個方法具有相同的名稱、相同引數以及相同返回型別,否則它們會被視作不同的方法。
簡而言之,如果我們更改簽名,那麼你將不能覆蓋父類的方法,如果你嘗試,則將執行父類的方法。
原因 - 如果更改簽名,那麼兩者會被視為不同的方法,且由於父類方法的副本可用在子類物件中,所以該副本會執行。
示例
class Super { void sample(int a, int b) { System.out.println("Method of the Super class"); } } public class MethodOverriding extends Super { void sample(int a, float b) { System.out.println("Method of the Sub class"); } public static void main(String args[]) { MethodOverriding obj = new MethodOverriding(); obj.sample(20, 20); } }
輸出
Method of the Super class
廣告