java 如何调用方法
调用方法的基本语法
在Java中,调用方法需要明确方法所属的对象或类(静态方法),并传递必要的参数。语法格式为:
对象名.方法名(参数列表); // 实例方法
类名.方法名(参数列表); // 静态方法
实例方法的调用
实例方法属于对象,需先创建类的实例:
ClassName obj = new ClassName();
obj.methodName(arg1, arg2);
示例:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
// 调用
Calculator calc = new Calculator();
int result = calc.add(3, 5); // 返回8
静态方法的调用
静态方法属于类,直接通过类名调用:
ClassName.staticMethodName(arg1, arg2);
示例:
public class MathUtils {
public static int multiply(int x, int y) {
return x * y;
}
}
// 调用
int product = MathUtils.multiply(4, 6); // 返回24
方法重载的调用
Java支持同名方法(参数不同),调用时根据参数类型匹配:
public class Printer {
public void print(String text) { /*...*/ }
public void print(int number) { /*...*/ }
}
// 调用
Printer printer = new Printer();
printer.print("Hello"); // 调用String版本
printer.print(100); // 调用int版本
递归方法的调用
方法内部调用自身需注意终止条件:
public class Factorial {
public int compute(int n) {
if (n <= 1) return 1;
return n * compute(n - 1); // 递归调用
}
}
// 调用
Factorial fact = new Factorial();
int result = fact.compute(5); // 返回120
可变参数方法的调用
使用省略号(...)表示可变参数,调用时可传任意数量同类型参数:

public class Sum {
public int sumNumbers(int... nums) {
int sum = 0;
for (int num : nums) sum += num;
return sum;
}
}
// 调用
Sum s = new Sum();
int total1 = s.sumNumbers(1, 2); // 返回3
int total2 = s.sumNumbers(1, 2, 3); // 返回6






