如何在 Java 中声明、定义和调用方法?
以下是 Java 中声明方法的语法。
语法
modifier return_type method_name(parameters_list){
//method body
}
其中,
modifier − 它定义了方法的访问类型,并且使用它是非必需的。
return_type − 方法可能会返回值。
method_name − 这是方法名称。方法签名由方法名称和参数列表组成。
parameters_list − 参数列表,它是某个方法的类型、顺序和数量。它们都是可选的,方法可能不包含任何参数。
method body − 方法体定义了方法用语句执行什么操作。
调用方法
要使用某个方法,应该调用它。有两种方法可以调用一个方法,即,方法返回值或不返回值(无返回值)。
实例
以下是展示如何定义方法以及如何调用它的示例 −
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** Returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2){
min = n2;
} else {
min = n1;
}
return min;
}
}
输出
Minimum value = 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP