在Java中,将原始类型传递给方法时,可以通过按值调用来完成。通过引用调用隐式传递对象。
这意味着当我们将原始数据类型传递给方法时,它将仅将值传递给函数参数,因此对参数所做的任何更改都不会影响实际参数的值。
Java中的对象是引用变量,因此对于对象,将传递作为对象引用的值。因此,不传递整个对象,而是传递其引用的对象。方法中对对象的所有修改都会修改堆中的对象。
class Add { int a; int b; Add(int x,int y)//参数化的构造函数 { a=x; b=y; } void sum(Add A1) //对象'A1'作为参数传递给函数'sum' { int sum1=A1.a+A1.b; System.out.println("Sum of a and b :"+sum1); } } public class classExAdd { public static void main(String arg[]) { Add A=new Add(5,8); /* Calls the parametrized constructor with set of parameters*/ A.sum(A); } }
输出结果
Sum of a and b :13
在创建类类型的变量时,我们仅创建对对象的引用。
当我们将此引用传递给函数时,接收该函数的参数将引用与参数所引用的对象相同的对象。