方法的定義:
- 方法是類或對象的行為特征的抽象。
- Java中的方法不能獨立存在,所有的方法必須定義在類中。
- 使用 “類名.方法” 或 “對象.方法” 的形式調用。
- 語法格式:
權限修飾符 返回值類型 方法名(參數類型 參數名) {
// 方法體
// 返回值
}
方法分類:
- 無參數無返回值
- 有參數無返回值
- 無參數有返回值
- 有參數有返回值
public class Method { public void aMethod() { System.out.println("無參數無返回值的方法"); } public void bMethod(int b) { System.out.println("有參數無返回值的方法"); } public int cMethod() { System.out.println("無參數有返回值的方法"); return 10; } public int dMethod(int d) { System.out.println("有參數有返回值的方法"); return d; } public static void main(String[] args) { int ret;
// 創建Method類的對象 Method md = new Method();
// 通過對象.方法調用 md.aMethod(); md.bMethod(10); ret = md.cMethod(); ret = md.dMethod(10); System.out.println(ret); } }
方法的參數:
方法可以沒有參數,或者有多個參數,參數類型可以是任意類型
方法參數也是局部變量
參數為引用數據類型時:
當對象實例作為參數傳遞給方法時,傳遞的是對象的引用,為地址傳遞,接受參數的方法可以改變參數的值。
參數為簡單數據類型時:
傳遞的是參數的副本,為值傳遞,接受參數的方法中不會改變參數的值。
public class MethodParam { /** * 方法的參數為基本數據類型時,傳遞的是值的副本(值拷貝) * 方法中不會改變元參數的值 */ public void swap(int a, int b) {//a, b為形參 int tmp; tmp = a; a = b; b = tmp; } int x = 100, y = 200; /** * 方法的參數為引用數據類型時,傳遞的對象的引用(傳地址) * 方法中可以改變參數的值 */ public void swap2(MethodParam mp) { int tmp = mp.x; mp.x = mp.y; mp.y = tmp; } public static void main(String[] args) { MethodParam mp = new MethodParam(); int m = 10, n = 20; System.out.println("交換前:a = "+m+",b = "+n); mp.swap(m, n);// m,n為實參 System.out.println("交換后:a = "+m+",b = "+n); System.out.println("交換前:x = "+mp.x+",y = "+mp.y); mp.swap2(mp); System.out.println("交換后:x = "+mp.x+",y = "+mp.y); } }