值传递是方法得到所有参数的拷贝,方法不能修改传递给它的任何参数变脸的内容。
引用传递是方法得到的是对象引用的拷贝,对象引用及其他的拷贝同时引用同一个对象(类型C++中的指针)
public class passByValue {
public static void main(String[] args) {
// 方法值作为参数传递
double percent =10;
tripleValue(percent);
System.out.println("percent:"+percent);
// 方法引用对象值作为参数传递
Employee employee = new Employee();
tripleSalary(employee);
System.out.println(employee.getSalary());
// 验证java是不是引用传递,如果是则交换成功,否则失败
Employee a = new Employee("a",200);
Employee b = new Employee("b",300);
swap(a,b);
System.out.println("a:"+a.toString());
System.out.println("b:"+b.toString());
}
public static void tripleValue(double x) {
x = 3 * x;
}
public static void tripleSalary(Employee x){
x.tripleSalry(200);
}
public static void swap(Employee x,Employee y){
Employee temp = x;
y= temp;
x = y;
}
}
class Employee{
private String name ;
private double salary;
public void tripleSalry(double salary){
this.salary = salary * 3;
}
public Employee(double salary) {
this.salary = salary;
}
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public Employee() {
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
// 值传递不会改变参数的值
percent:10.0
// 引用对象
600.0
//swap结果为失败
a:Employee{name='a', salary=200.0}
b:Employee{name='b', salary=300.0}
结论:Java对对象采用的不是引用传递,而是值传递