4-4面向物件程式設計(上)----再談方法(2)--可變形參的方法
阿新 • • 發佈:2021-01-21
2.可變形參的方法
(1)JDK 5.0新增的內容,允許直接定義能和多個實參相匹配的形參。從而,可以用一種更簡單的方式,來傳遞個數可變的實參。
(2)具體使用
①可變個數形參的格式:資料型別 … 變數名。
②當呼叫可變個數形參的方法時,傳入的引數個數可以是:0個,1個,2個……
③可變個數形參的方法與本類中方法名相同,形參不同的方法之間構成的過載
④可變個數形參的方法與本類中方法名相同,形參型別也相同的陣列之間不構成過載,他們二者不能共存。
⑤可變個數形參在方法的形參中,必須宣告在末尾。
⑥可變個數形參在方法中的形參中,最多隻能宣告一個可變形參。
程式碼:
public class MethodArgsTest {
public static void main(String[] args) {
MethodArgsTest test = new MethodArgsTest();
test.show(12);// 1
test.show("hello");// 2
test.show("hello", "world");// 3
test.show();// 3
test.show("AA", "BB", "CC");
}
public void show(int i) {// 對應1
}
// 註釋之後不報錯,採用下面的
public void show(String s) {// 對應2
System.out.println("show(String)");
}
public void show(String... strs) {// 對應3
System.out.println("show(String ... strs)");
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
}
// 與上面的無法構成過載
// public void show(String[] strs) {
//
// }
// The variable argument type String of the method show must be the last
// parameter
// public void show(String ... strs, int i) {
//
// }//必須宣告在最後--->(int i,String ... strs)
}
輸出:
show(String)
show(String ... strs)
hello
world
show(String ... strs)
show(String ... strs)
AA
BB
CC