如何调用java方法
调用 Java 方法的基本步骤
在 Java 中调用方法需要明确方法的定义、访问权限以及调用方式。以下是具体实现方法:
定义方法
方法需在类中定义,包含返回类型、方法名和参数列表。例如:
public class Example {
public void printMessage() {
System.out.println("Hello, World!");
}
}
实例方法调用
通过类的实例对象调用非静态方法:
Example example = new Example();
example.printMessage(); // 输出: Hello, World!
静态方法调用
静态方法属于类而非实例,可直接通过类名调用:
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
int result = MathUtils.add(3, 5); // 返回 8
带参数的方法调用
传递参数需与方法的参数列表匹配:
public class Calculator {
public int multiply(int x, int y) {
return x * y;
}
}
Calculator calc = new Calculator();
int product = calc.multiply(4, 6); // 返回 24
方法重载调用
同一类中允许同名方法但参数不同:
public class Printer {
public void print(String text) {
System.out.println(text);
}
public void print(int number) {
System.out.println(number);
}
}
Printer printer = new Printer();
printer.print("Text"); // 调用 String 参数方法
printer.print(100); // 调用 int 参数方法
递归方法调用
方法内部调用自身需注意终止条件:

public class Factorial {
public int compute(int n) {
if (n <= 1) return 1;
return n * compute(n - 1);
}
}
Factorial factorial = new Factorial();
int result = factorial.compute(5); // 返回 120
关键注意事项
- 静态方法无需实例化,但非静态方法必须通过对象调用。
- 方法参数传递为值传递(基本类型)或引用传递(对象类型)。
- 访问权限(
public/private/protected)影响方法能否被调用。






