对于基本数据类型来说,直接拷贝了一份参数进行操作,所以不会对传进去的参数有什么影响。
对于对象的引用来说,拷贝的是对象的引用,如果在函数中对它的引用进行了操作的话,会改变原来对象的值。
下面有个例子可能证明,对象传进去进行的是对象引用的拷贝,而不是进行了引用调用
package com.fengkai.www;
import javax.swing.plaf.synth.SynthSpinnerUI;
class Emplouy
{
private String name;
private double salary;
public Emplouy(String n, double s)
{
name = n;
salary = s;
}
public String getName()
{
return name;
}
public double getSalary() {
return salary;
}
public void raiseSalary(double byPercent) {
double raise = salary * byPercent /100;
salary += raise;
}
}
public class ParamTest {
public static void tripleSalary(double x) {
x = 3 * x;
System.out.println("End of method: x=" + x);
}
public static void tripleSalary(Emplouy x) {
x.raiseSalary(200);
System.out.println("End of method: x=" + x.getSalary());
}
public static void swap(Emplouy x, Emplouy y) {
Emplouy temp = x;
x = y;
y = temp;
System.out.println("End of method: x=" + x.getName());
System.out.println("End of method: y=" + y.getName());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Test01
System.out.println("Testing tripleValue");
double precent = 10;
System.out.println("Before: precent =" + precent);
tripleSalary(precent);
System.out.println("After: percent =" + precent);
//Test02
System.out.println("\nTseting tripleSalary:");
Emplouy harry = new Emplouy("Harry", 50000);
System.out.println("Before: salary=" + harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary=" + harry.getSalary());
//Test03
System.out.println("\nTesting swap:");
Emplouy a = new Emplouy("Alice", 70000);
Emplouy b = new Emplouy("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());
}
}