Java中方法引數傳遞詳析

Pop_Rain發表於2017-06-26

一個方法不能修改一個基本資料型別的引數(即數值型和布林型)

一個方法可以改變一個物件引數的狀態

一個方法不能讓物件引數引用一個新的物件

事實上,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 //沒變

相關文章