Java支持以下几种参数传递类型:
- 值传递(传递的是实际值):基本数据类型和不可变对象(如String)都是通过值传递。在方法调用时,会将实际参数的副本传递给方法,方法对副本的修改不会影响到原始值。
示例代码:
public class Main {
public static void main(String[] args) {
int num = 10;
System.out.println("Before method call: " + num);
changeValue(num);
System.out.println("After method call: " + num);
}
public static void changeValue(int value) {
value = 20;
System.out.println("Inside method: " + value);
}
}
输出结果:
Before method call: 10
Inside method: 20
After method call: 10
- 引用传递(传递的是引用的副本):对象类型(如数组、自定义类等)通过引用传递。在方法调用时,会将引用的副本传递给方法,方法可以修改引用指向的对象的属性,但不能修改引用本身。
示例代码:
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println("Before method call: " + Arrays.toString(array));
changeArray(array);
System.out.println("After method call: " + Arrays.toString(array));
}
public static void changeArray(int[] arr) {
arr[0] = 10;
System.out.println("Inside method: " + Arrays.toString(arr));
}
}
输出结果:
Before method call: [1, 2, 3]
Inside method: [10, 2, 3]
After method call: [10, 2, 3]
需要注意的是,虽然引用传递可以修改对象的属性,但不能修改引用本身。例如,将引用指向一个新的对象,原始引用不会发生变化。
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass(10);
System.out.println("Before method call: " + obj.getValue());
changeObject(obj);
System.out.println("After method call: " + obj.getValue());
}
public static void changeObject(MyClass obj) {
obj = new MyClass(20);
System.out.println("Inside method: " + obj.getValue());
}
}
class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
输出结果:
Before method call: 10
Inside method: 20
After method call: 10
在上述代码中,尽管在changeObject
方法中将obj
引用指向了一个新的对象,但在main
方法中原始的obj
引用并没有发生变化。GPT-4 Plus账号大大大降价了!
发布者:admin,如若转载,请注明出处:https://ai1024.vip/42738.html