Java 中的按值调用和按引用调用
java 8object oriented programmingprogramming更新于 2024/10/13 14:59:00
按值调用意味着使用参数作为值来调用方法。通过这种方式,参数值被传递给参数。
而按引用调用意味着使用参数作为引用来调用方法。通过这种方式,参数引用被传递给参数。
在按值调用中,对传递的参数所做的修改不会反映在调用者的作用域中,而在按引用调用中,对传递的参数所做的修改是持久的,并且更改会反映在调用者的作用域中。
以下是按值调用的示例 −
以下程序显示了按值传递参数的示例。即使在方法调用之后,参数的值仍保持不变。
示例 - 按值调用
public class Tester{ public static void main(String[] args){ int a = 30; int b = 45; System.out.println("Before swapping, a = " + a + " and b = " + b); // 调用 swap 方法 swapFunction(a, b); System.out.println("
**Now, Before and After swapping values will be same here**:"); System.out.println("After swapping, a = " + a + " and b is " + b); } public static void swapFunction(int a, int b) { System.out.println("Before swapping(Inside), a = " + a + " b = " + b); // 将 n1 与 n2 交换 int c = a; a = b; b = c; System.out.println("After swapping(Inside), a = " + a + " b = " + b); } }
输出
这将产生以下结果 −
Before swapping, a = 30 and b = 45 Before swapping(Inside), a = 30 b = 45 After swapping(Inside), a = 45 b = 30 **Now, Before and After swapping values will be same here**: After swapping, a = 30 and b is 45
示例 - 按引用调用
Java 只使用按值调用,同时传递引用变量。它创建引用的副本并将其作为值传递给方法。由于引用指向对象的同一地址,因此创建引用的副本无害。但如果将新对象分配给引用,则不会反映出来。
public class JavaTester { public static void main(String[] args) { IntWrapper a = new IntWrapper(30); IntWrapper b = new IntWrapper(45); System.out.println("Before swapping, a = " + a.a + " and b = " + b.a); // 调用交换方法 swapFunction(a, b); System.out.println("
**Now, Before and After swapping values will be different here**:"); System.out.println("After swapping, a = " + a.a + " and b is " + b.a); } public static void swapFunction(IntWrapper a, IntWrapper b) { System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a); // 将 n1 与 n2 交换 IntWrapper c = new IntWrapper(a.a); a.a = b.a; b.a = c.a; System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a); } } class IntWrapper { public int a; public IntWrapper(int a){ this.a = a;} }
这将产生以下结果 −
输出
Before swapping, a = 30 and b = 45 Before swapping(Inside), a = 30 b = 45 After swapping(Inside), a = 45 b = 30 **Now, Before and After swapping values will be different here**: After swapping, a = 45 and b is 30