W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
在同一類中具有多個具有相同名稱的方法稱為方法重載。
類中具有相同名稱的方法可以是聲明的方法,繼承的方法或兩者的組合。
重載方法必須具有不同數量的參數,不同類型的參數或兩者。
方法的返回類型,訪問級別和throws子句對使其成為重載方法沒有任何影響。
import java.io.IOException; class MyClass { public void m1(int a) { // Code goes here } public void m1(int a, int b) { // Code goes here } public int m1(String a) { // Code goes here return 0; } public int m1(String a, int b) throws IOException { // Code goes here return 0; } }
下面的代碼顯示了如何使用重載。
public class Main { public double add(int a, int b) { System.out.println("Inside add(int a, int b)"); double s = a + b; return s; } public double add(double a, double b) { System.out.println("Inside add(double a, double b)"); double s = a + b; return s; } public static void main(String[] args) { Main ot = new Main(); int i = 1; int j = 1; double d1 = 10.42; float f1 = 22.3F; float f2 = 24.5F; short s1 = 22; short s2 = 26; ot.add(i, j); ot.add(d1, j); ot.add(i, s1); ot.add(s1, s2); ot.add(f1, f2); ot.add(f1, s2); } }
上面的代碼生成以下結果。
有時,重載方法和自動類型擴展可能會混淆編譯器,導致編譯器錯誤。
class Adder { public double add(int a, double b) { return a + b; } public double add(double a, int b) { return a + b; } } public class Main { public static void main(String[] args) { Adder a = new Adder(); // double d = a.add(2, 3); // A compile-time error double d1 = a.add((double) 2, 3); // OK. Will use add(double, int) double d2 = a.add(2, (double) 3); // OK. Will use add(int, double) } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: