| 方法類型 | 調用語法 | 適用場景 |
|---|---|---|
| 靜態方法 | ClassName.method() 或 method() | 工具類、無狀態邏輯 |
| 實例方法 | new ClassName().method() | 需要對象狀態的業務邏輯 |
| 內部類方法 | new OuterClass().new InnerClass().method() | 封裝邏輯、訪問外部類成員 |
public class HelloWord {
public static void main(String[] args) {
for (int i=0; i<20; i++) {
int result = Add(0, 1); // 直接調用
System.out.println("Hello " + result);
}
}
private static int Add(int x, int y) { return x+y; }
}
public class HelloWord {
public static void main(String[] args) {
HelloWord hw = new HelloWord(); // 實例化
for (int i=0; i<20; i++) {
int result = hw.Add(0, 1); // 通過實例調用
System.out.println("Hello " + result);
}
}
private int Add(int x, int y) { return x+y; } // 無 static
}
public class Test {
public int Add(int x, int y) { return x+y; }
public static int Sub(int x, int y) { return x-y; }
}
public class HelloWord {
public static void main(String[] args) {
Test test = new Test();
int r1 = test.Add(5, 6); // 實例方法
int r2 = Test.Sub(10, 3); // 靜態方法(類名調用)
System.out.println(r1 + ", " + r2);
}
}
Java 唯一支持 值傳遞。基本類型傳值副本,引用類型傳引用副本(指向同一對象)。
public static void swap(int a, int b) {
int t = a; a = b; b = t; // 僅交換局部副本
}
public static void modify(User u) {
u.setName("新名"); // 修改對象內部狀態,外部可見
u = new User(); // 重新指向新對象,外部不可見
}
static