1 语法格式:
修饰符 返回值类型 方法名(参数类型 参数名1, 参数名类型 参数名2, ...){
执行语句
.......
return 返回值;
}
// 1. 无返回值无参数
public void myFunc(){
......
}
// 2. 有返回值无参数
public int myFunc(){
....
return int_num;
}
// 3. 无返回值有参数
public void myFunc(){
...
}
// 4. 有返回值有参数
public int myFunc(){
....
return int_num;
}
2 方法重载
在一个类中可以定义多个名称相同的方法,但是参数的类型或参数个数必须不同。
例如:
public static int add(int x, int y){....} // 两个整数加法
public static int add(int x, int y, int z){...} // 三个整数加法
public static double add(double x, double y){...} // 两个小数加法
2.1 参数传递
// 1. 调用方法时,传递的是基本数据类型数据
public class TestSth {
public static void main(String[] args) {
int a=5;
int b=10;
add(a,b); // 调用方法
System.out.println("a="+a); // a=5
System.out.println("b="+b); // b=10
}
public static void add(int a,int b) {
a=200;
b=300;
}
}
// 2. 调用方法传递的参数是引用数据类型数据
public class TestSth1 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3 };
change(arr); // 调用方法
System.out.println("arr[0]=" + arr[0]); // 2
System.out.println("arr[1]=" + arr[1]); // 4
System.out.println("arr[2]=" + arr[2]); // 6
}
public static void change(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
}
}
上面两段程序可以看出:
- 调用方法时,如果传入的数值为基本数据类型(包含String类型),形式参数的改变对实际参数没有影响。
- 如果传入的数值为引用数据类型(String类型除外),形式参数的改变对实际参数有影响。