1. 為什麼需要成員方法?
Method02.java
- 看一個需求:
請周遊一個數組 , 輸出數組的各個元素值。
- 解決思路 1:傳統的方法,就是使用單個
循環,将數組輸出,看看問題是什麼?for
public class Method02 {
public static void main(String[] args) {
int[][] map = {{0, 1, 1}, {1, 1, 1}, {1, 1, 3}};
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
}

- 解決思路 2:定義一個類
,然後寫一個成員方法,調用方法實作,看看效果又如何。MyTools
public class Method02 {
public static void main(String[] args) {
int[][] map = {{0, 1, 1}, {1, 1, 1}, {1, 1, 3}};
Mytools mytools = new Mytools();
mytools.printArr(map);
mytools.printArr(map);
}
}
//把輸出的功能,寫到一個方法中,然後再調用該方法
class Mytools{
//方法,接收一個二維數組
public void printArr(int [][] map){
System.out.println("----------------------");
//對傳入的map數組進行周遊輸出
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
}
- 可以從重複調用方法
2. 成員方法的好處
1) 提高代碼的複用性
2) 可以将實作的細節封裝起來,然後供其他使用者來調用即可