编程语言实现的参数传递方法
- call by value
- call by reference
传递的参数类型
- primitive type (numbers & boolean values)
- Object reference
Java是call by value(值传递), 而且object reference are passed by value
三条准则
- 方法不能改变原始类型参数的值
- 方法可以改变引用类型参数的状态
- 方法不能使引用类型的参数指向新的对象
测试例子
public class ParamTest {
public static void main(String[] args){
/**
* Test 1: Methods can't modify numeric parameters
*/
System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before: percent=" + percent);
tripleValue(percent);
System.out.println("After: percent=" + percent);
/**
* Test 2: Methods can change the state of object parameters
*/
System.out.println("\nTesting tripleSalary:");
Employee harry = new Employee("Harry", 50000);
System.out.println("Before: salary=" + harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary=" + harry.getSalary());
/**
* Test 3: Methods can't attach new objects to object parameters
*/
System.out.println("\nTesting swap:");
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());
}
private static void swap(Employee x, Employee y) {
Employee temp = x;
x=y;
y=temp;
System.out.println("End of method: x=" + x.getName());
System.out.println("End of method: y=" + y.getName());
}
private static void tripleSalary(Employee x) {
x.raiseSalary(200);
System.out.println("End of method: salary=" + x.getSalary());
}
private static void tripleValue(double x) {
x=3*x;
System.out.println("End of Method X= "+x);
}
}
Testing tripleValue:
Before: percent=10.0
End of Method X= 30.0
After: percent=10.0
Testing tripleSalary:
Before: salary=50000.0
End of method: salary=150000.0
After: salary=150000.0
Testing swap:
Before: a=Alice
Before: b=Bob
End of method: x=Bob
End of method: y=Alice
After: a=Alice
After: b=Bob