Java参数传递
java中采用的是值传递方式,方法形参得到的是外部实参的一个拷贝。
1)方法不能修改基本数据类型的参数(即数字型或者布尔型)
public class HelloWorld {
public static void main(String[] args) {
int x = 3;
doubleNum(x);
System.out.println(x);
}
private static void doubleNum (int x) {
x = 2*x;
}
}
在这个测试类中,原本希望通过调用doubleNum
方法将实际参数x
扩大一倍。但是输出的结果还是3
。这一点是显而易见的。
2)方法可以改变对象参数的状态
当把一个类对象作为实际参数传入方法中的形参,如果对形参类的属性进行了修改,那么外面的实参类也会相应的变更。
这里要强调一个概念:对象变量和对象引用,我们通过new
操作符得到的对象变量可以理解为一个无名变量,存放在堆空间中,这个是对象变量。
然后定义一个对象引用指向这个无名变量,后面我们就通过这个引用来操作这个无名对象。
public class HelloWorld {
public static void main(String[] args) {
Student ming = new Student("ming");
Student hong = new Student("hong");
change(ming, hong);
System.out.println(ming.name);
System.out.println(hong.name);
}
static void change(Student a, Student b) {
a.name = "hong";
b.name = "ming";
}
}
class Student {
public String name;
public Student(String name){
this.name = name;
};
}
可以改变成功。
3)方法不能让一个对象参数引用另外一个对象参数
public class HelloWorld {
public static void main(String[] args) {
Student ming = new Student("ming");
Student hong = new Student("hong");
swap(ming, hong);
System.out.println(ming.name);
System.out.println(hong.name);
}
static void swap(Student a, Student b) {
Student temp;
temp = a;
a = b;
b = temp;
}
}
class Student {
public String name;
public Student(String name){
this.name = name;
};
}
这里想通过swap函数,交换两个学生对象引用,但是失败了。
注意:C++可以通过引用的方式交换两个对象,void swap(Student& a, Student& b)
因为C++中的引用是实际对象变量的一个别名,他不是一个变量。