-
方法的定义
修饰符 返回值类型 方法名 (参数类型 参数名){ ... 方法体 ... return 返回值; }
- 修饰符:修饰符,这是可选的,告诉编译器如何调用该方法。定义了该方法的访问类型。
- 返回值类型:方法可能会返回值。returnValueType是方法返回值的数据类型。有些方法执行所需的操作,但没有返回值。在这种情况下,returnValueType是关键字void。
- 方法名:是方法的实际名称。方法名和参数表共同构成方法签名。
- 参数类型:参数像是一个占位符。当方法被调用时,传递值给参数。这个值被称为实参或变量。参数列表是指方法的参数类型、顺序和参数的个数。参数是可选的,方法可以不包含任何参数。
- 方法体:方法体包含具体的语句,定义该方法的功能。
例:
/** * 返回两个整型变量数据的较大值 * @param num1 * @param num2 * @return */ public static int max(int num1, int num2) { int result; if (num1 > num2) { result = num1; }else { result = num2; } return result; }
-
方法调用
例:public static void main(String[] args) { int i = 5; int j = 2; int k = max(i, j); System.out.println("The maximum between " + i + " and " + j + " is " + k); }
-
void 关键字
例:public class TestVoidMethod { public static void main(String[] args) { printGrade(78.5); } public static void printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } } }
-
通过值传递参数
例:
public class TestPassByValue { public static void main(String[] args) { int num1 = 1; int num2 = 2; System.out.println("Before swap method, num1 is " + num1 + " and num2 is " + num2); // 调用swap方法 swap(num1, num2); System.out.println("After swap method, num1 is " + num1 + " and num2 is " + num2); } /** * 交换两个变量的方法 * @param n1 * @param n2 */ public static void swap(int n1, int n2) { System.out.println("\tInside the swap method"); System.out.println("\t\tBefore swapping n1 is " + n1 + " n2 is " + n2); // 交换 n1 与 n2的值 int temp = n1; n1 = n2; n2 = temp; System.out.println("\t\tAfter swapping n1 is " + n1 + " n2 is " + n2); } }
-
方法重载
例:
public static double max(double num1, double num2) { double result; if (num1 > num2) { result = num1; }else { result = num2; } return result; }
-
构造方法
例:
public class HelloConstruction { /** * 成员变量 */ public int num1; /** * 构造函数 * 可以用于初始化成员变量 */ public HelloConstruction(int num1) { this.num1 = num1; } public static void main(String[] args) { HelloConstruction construction = new HelloConstruction(10); System.out.println("通过构造函数初始化的成员变量值为:" + construction.num1); } }
-
可变参数