代码取自Java核心技术卷一,第四章类与对象
方法参数分别为基本数据类型、对象的引用变量
一、基本数据类型,按值传送,没有改变原数据
二、对象引用变量被按值传送进方法,原harry变量指向一个对象, 进入方法,x变量也指向同一个变量,方法中对x指向的对象进行改动,所以当使用方法外的原Harry变量操作此对象的时候,此对象已经是通过方法对其进行过处理了的
三、依然是对象引用变量被按值传送进方法,但是方法内没有对两个新copy的对象引用变量(形参)所指向的两个对象进行改动,只是交换了两个方法内的引用变量之间的指向方向,所以在方法内我们看到他们好像是进行了交换,实际上只是两个方法内指向对象的引用变量进行了互换,当我们在方法外再来使用原有的两个对象引用变量的时候,他们并没有进行过交换
/**
* This program demonstrates parameter passing in Java.
* @version 1.01 2018-04-10
* @author Cay Horstmann
*/
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:");
var 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:");
var a = new Employee("Alice", 70000);
var 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) // doesn't work
{
x = 3 * x;
System.out.println("End of method: x=" + x);
}
public static void tripleSalary(Employee x) // works
{
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 // simplified Employee class
{
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 byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
}