在Java中,有多种不同的方法可以进行参数传递。下面是一些常见的方法传递的示例代码:
值传递:
public static void main(String[] args) {
int num = 5;
System.out.println("Before calling method: " + num);
changeValue(num);
System.out.println("After calling method: " + num);
}
public static void changeValue(int value) {
value = 10;
System.out.println("Inside method: " + value);
}
输出:
Before calling method: 5
Inside method: 10
After calling method: 5
在值传递中,参数的值被复制到方法中,对参数的修改不会影响原始值。
引用传递:
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println("Before calling method: " + Arrays.toString(array));
changeArray(array);
System.out.println("After calling method: " + Arrays.toString(array));
}
public static void changeArray(int[] arr) {
arr[0] = 10;
System.out.println("Inside method: " + Arrays.toString(arr));
}
输出:
Before calling method: [1, 2, 3]
Inside method: [10, 2, 3]
After calling method: [10, 2, 3]
在引用传递中,参数的引用被传递到方法中,对参数的修改会影响原始值。
对象传递:
public class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public static void main(String[] args) {
MyClass obj = new MyClass(5);
System.out.println("Before calling method: " + obj.getValue());
changeObject(obj);
System.out.println("After calling method: " + obj.getValue());
}
public static void changeObject(MyClass obj) {
obj.setValue(10);
System.out.println("Inside method: " + obj.getValue());
}
输出:
Before calling method: 5
Inside method: 10
After calling method: 10
在对象传递中,参数的引用被传递到方法中,对参数的修改会影响原始对象的状态。
上一篇:不同类型的对象数组