首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 可變參數完整指南:語法、重載、建構子與實戰範例

     編輯:Java 相關知識

什麼是可變參數?

JDK 1.5 引入 varargs(型別... 參數名),允許方法接受 0 至多個同型別參數,編譯器自動轉為陣列。解決過去需撰寫大量重載方法或改用陣列/集合的困擾。

基本語法與規則

修飾字 回傳型別 方法名(固定參數列表, 型別... 參數名) { ... }
  • ... 必須是三個點,緊接在型別後
  • 可變參數必須置於參數列表最後
  • 方法內以陣列方式存取(for (型別 e : 參數名))
  • 呼叫時可傳 0 個、多個引數或陣列

核心範例

列印邀請函

void printInvitation(String... names) {
  for (String name : names) {
    makeCard(name);
    System.out.println("Recording info: invitation card has been printed for " + name);
  }
}

// 呼叫
printInvitation("李剛", "David Smith");
printInvitation("Greg Wu", "Paul Nguyen", "Liu Wei", "張新");
printInvitation(); // 無參數,不執行迴圈

計算整數總和

public static int sumInts(int... numbers) {
  int sum = 0;
  for (int num : numbers) sum += num;
  return sum;
}

混合固定參數與可變參數

public void totalTax(String name, double rate, double... amounts) {
  double total = 0;
  for (double amt : amounts) total += amt;
  double tax = total * rate;
  System.out.println("Name: " + name + "\nTotal: " + total + "\nTax: " + tax);
}

進階應用

建構子與覆寫

public class Supper {
  public Supper(char... characters) { ... }
}

class SubClass extends Supper {
  public SubClass(char... characters) { ... } // 可覆寫
  // 無法用 super(char...) 呼叫父類別建構子
}

方法重載

可變參數方法可正常重載,遵循一般重載規則(參數型別/數量不同):

void someMethod(int count, double... prices) { ... }
void someMethod(double... prices) { ... } // 重載
double someMethod(String... names) { ... } // 重載

實戰綜合範例:跑車訂購系統

列舉定義

enum ColorType {
  WHITE { String getDescription() { return "有淺白、暗白、和亮白可選"; } },
  SILVER { String getDescription() { return "有銀白、銀灰、純銀色可選"; } },
  BLACK { String getDescription() { return "有深黑和淺黑可選"; } };
  abstract String getDescription();
}

enum PaymentType {
  CASH("有10%特別優惠"), CREDIT("接受所有信用卡"), LOAN("貸款利息為.56%");
  final private String payment;
  PaymentType(String p) { payment = p; }
  public String getPayment() { return payment; }
}

使用可變參數處理選項

class SportCar {
  SportCarType type; ColorType color; PaymentType payment;

  public SportCar(String... choices) { // 可變參數
    processInfo(choices);
  }

  private void processInfo(String[] choices) {
    if (choices.length == 1) processType(choices[0]);
    else if (choices.length == 2) { processType(choices[0]); processColor(choices[1]); }
    else if (choices.length == 3) { processType(choices[0]); processColor(choices[1]); processPayment(choices[2]); }
  }
  // processType, processColor, processPayment 解析字串設定列舉值
  // toString() 格式化輸出
}

驅動程式與執行結果

public class VarargsApp {
  public static void main(String[] args) {
    SportCar yourCar = new SportCar("P");           // 保時捷
    SportCar myCar = new SportCar("J", "S");        // 捷豹 + 銀色
    SportCar herCar = new SportCar("F", "B", "C");  // 法拉利 + 黑色 + 現金
    System.out.println("你要的跑車資訊:\n" + yourCar);
    System.out.println("我要的跑車資訊:\n" + myCar);
    System.out.println("她要的跑車資訊:\n" + herCar);
  }
}

輸出:

你要的跑車資訊:
製造國:德國
價格:$120,000.00

我要的跑車資訊:
製造國:英國
價格:$110,000.00
有銀白、銀灰、純銀色可選

她要的跑車資訊:
製造國: 義大利
價格:$150,000.00
有深黑和淺黑可選
有10%特別優惠

注意事項與最佳實務

  • 避免模稜兩可的重載(如 foo(int...) vs foo(Integer...))
  • 可變參數本質是陣列,傳入 null 會導致 NPE,建議檢查 if (args == null || args.length == 0)
  • 效能敏感場合可考慮固定參數 + 陣列,避免隱含陣列建立開銷
  • 文件化說明可接受的參數數量與語意

結語

可變參數大幅簡化 API 設計,配合列舉、重載、建構子等特性,能撰寫出靈活且可讀性高的程式碼。掌握其語法規則與陣列本質,善用於參數數量不固定的場景(如格式化、聚合計算、建構器選項)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved