以前写C代码的时候对于方法参数是值传递还是引用传递非常明了,因为有&运算符表示。但是在java里面没有了,就觉得很难理解。
大致书上的总结:
1 一个方法不能修改基础数据类型的参数(这里指的是原参);
2 一个方法可以修改一个对象参数的状态(对象作为参数传入,则是对象的引用,但是只能通过引用对象的成员函数来改变对象的成员);
3 一个方法不能实现让对象参数引用一个新的对象(即不能在函数内部让传入参数引用一个新的对象);
我还是不能看懂,为什么。。
代码测试如下:
package ArralListTest;
import java.util.*;
public class ArrayListTest {
/**
* @param args
*/
public static void main(String[] args) {
//test method call by
System.out.println("Testing tripleValue:");
double percent = 10;
System.out.println("Before: percent=" + percent);
tripleValue(percent);
System.out.println("After: percent=" + percent);
System.out.println("
Testing tripleSalary:");
Employee harry = new Employee("Harry",5000,1987,12,11);
System.out.println("Befor: salary=" + harry.getSalary());
tripleSalary(harry);
System.out.println("After: salary=" + harry.getSalary());
System.out.println("
Testing swap:");
Employee a = new Employee("Alice",5000,1987,12,11);
Employee b = new Employee("Bob",5000,1987,12,11);
System.out.println("Befor: a=" + a.getName());
System.out.println("Befor: b=" + b.getName());
swap(a,b);
System.out.println("After: a=" + a.getName());
System.out.println("After: b=" + b.getName());
//test method call by
}
public static void tripleValue(double x){
x = 3*x;
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;
System.out.println("End of method:x="+x.getName());
System.out.println("End of method:y="+y.getName());
}
}
class Employee{
public Employee(String n, double s ,int year, int month,int day){
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year,month - 1,day);
hireDay = calendar.getTime();
}
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public Date getHireDay(){
return hireDay;
}
public void raiseSalary(double byPercent){
double raise = salary * byPercent /100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}