如何在 Java 中声明、定义和调用方法?
以下是 Java 中声明方法的语法。
语法
modifier return_type method_name(parameters_list){ //method body }
其中,
modifier − 它定义方法的访问类型,可选择使用。
return_type − 方法可能返回值。
method_name − 这是方法名称。方法签名由方法名称和参数列表组成。
parameters_list − 参数列表,即方法的类型、顺序和数量。这些是可选的,方法可以不包含任何参数。
method body − 方法主体定义了方法通过语句执行的操作。
调用方法
要使用某个方法,应予以调用。调用方法有两种方式,即方法返回一个值或不返回任何值(无返回值)。
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
示例
以下是演示如何定义方法并如何调用该方法的示例 −
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
广告