【六】方法
文章目錄
- 1. 什么是方法
- 2. 方法的聲明和調用
- 3. 方法的重載
- 4. 可變參數列表
1. 什么是方法
方法,就是用來解決一類問題的代碼的有序組合,是一個功能模塊。
Scanner sc = new Scanner(System.in); sc.nextInt(); sc.next();System.out.println();方法是寫在類里面的。
2. 方法的聲明和調用
方法的聲明
- 語法格式:
訪問修飾符 返回類型 方法名(參數列表){
方法體
}
方法分類
根據方法是否帶參數、是否返回值,可分為四類:
- 無參無返回值方法
- 無參帶返回值方法 public int area(){}
- 帶參無返回值方法 public void max(float a,float b){}
- 帶參帶返回值方法 public int fac(int n){}
3. 方法的重載
方法名相同,參數列表不同。(與返回類型無關)
public int hello(float f1){} public void hello(){} public void hello(String s){} public void hello(float f1,float f2){}4. 可變參數列表
public void sum(int… n){int sum = 0;for(int i:n){sum += i;}System.out.println(sum); }可變參數要放在參數列表最后面:
public void sum(int a,int b,int… n){}可以把數組傳遞給可變參數列表:
int[] a = [1,2,3]; fun.sum(1,2,a); // fun為實例化后的對象一個方法中只能有一個可變參數。
可變參數列表的方法是在最后被訪問的。
總結
- 上一篇: sprongboot mysql登录注册
- 下一篇: testng查看覆盖率_使用Cobert