Java中方法参数传递详析

时间:2021-10-15 21:24:52

一个方法不能修改一个基本数据类型的参数(即数值型和布尔型)

一个方法可以改变一个对象参数的状态

一个方法不能让对象参数引用一个新的对象

事实上,java各种参数传递都是值传递(一种拷贝的传递),而不是引用,详见核心技术卷一 P123。辅助理解代码如下:

public class Test
{
public static void main(String args[])
{
System.out.println("Testing1:");
double percent = 10;
System.out.println("before pecent=" + percent);
tripleValue(percent);
System.out.println("after pecent=" + percent);

System.out.println("Testing2:");
Employee Herry = new Employee("Herry", 70000);
System.out.println("before: salary=" + Herry.getSalary());
tripleSalary(Herry);
System.out.println("after: salary=" + Herry.getSalary());

System.out.println("Testing3:");
Employee a = new Employee("Alice", 70000);
Employee b = new Employee("Bob", 60000);
System.out.println("before: a=" + a.getName());
System.out.println("before: b=" + b.getName());
swap(a, b);
System.out.println("after: a=" + a.getName());
System.out.println("after: b=" + b.getName());
}
public static void tripleValue(double x)
{
x *= 3;
System.out.println("end of method: x=" + x);
}

public static void tripleSalary(Employee x)
{
x.raiseSalary(200);
System.out.println("end of method: salary=" + x.getSalary());
}

public static void swap(Employee x, Employee y)
{
Employee temp = x;
x = y;
y = temp;
}
}

class Employee
{
private String name;
private double salary;

public Employee(String n, double s)
{
name = n;
salary = s;
}

public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void raiseSalary(double percent)
{
salary *= (1 + percent/100);
}
}
output:

Testing1:
before pecent=10.0
end of method: x=30.0
after pecent=10.0 //没变
Testing2:
before: salary=70000.0
end of method: salary=210000.0
after: salary=210000.0 //变了
Testing3:
before: a=Alice
before: b=Bob
after: a=Alice
after: b=Bob //没变