成員方法是類別行為的封裝,相當於 C/C++ 的函式。掌握方法定義、多載、存取層級、靜態特性與建構子/解構子機制,是撰寫良好物件導向程式的基石。
修飾詞 回傳型別 方法名稱(參數列表) {
// 方法本體
return 回傳值; // void 型別可省略
}
void;布林型常用於表示成功/失敗。public class Rectangle {
private int width, height, area;
// 建構子
public Rectangle(int w, int h) {
width = w; height = h;
area = getArea(w, h);
}
// 私有輔助方法
private int getArea(int w, int h) {
return w * h;
}
// 公開行為
public void drawRect() {
for (int i = width; i > 0; i--) System.out.print("#");
System.out.println();
for (int i = height - 2; i > 0; i--) {
System.out.print("#");
for (int j = width - 2; j > 0; j--) System.out.print(" ");
System.out.println("#");
}
for (int i = width; i > 0; i--) System.out.print("#");
System.out.println();
}
}
| 修飾詞 | 同類 | 同套件 | 子類別 | 其他 |
|---|---|---|---|---|
private | ✓ | ✗ | ✗ | ✗ |
package-private(預設) | ✓ | ✓ | ✗ | ✗ |
protected | ✓ | ✓ | ✓ | ✗ |
public | ✓ | ✓ | ✓ | ✓ |
最佳實務:欄位預設 private,提供 public getter/setter 控制存取(如 setWidth(int w))。
同一類別中定義多個同名但參數列表不同(型別、數量、順序)的方法:
void draw(int x, int y);
void draw(float x, float y);
void draw(int x, int y, Color c);
編譯器依呼叫時的實際引數型別決定呼叫哪個版本(靜態繫結)。
static int version = 1;)。this 參考,無法直接存取非靜態成員。透過 類別名.方法() 呼叫(如 Math.max()、System.out.println())。public,支援多載。public Rectangle(int w, int h) { width = w; height = h; }
Java 9 起標記為 @Deprecated,不建議使用。GC 不保證執行時機,資源釋放請用 try-with-resources、AutoCloseable 或 Cleaner API。