java方法參數詳析


title: java方法參數詳析
date: 2017-06-26 10:53:26
updated: 2020-03-15 16:23:54
categories: java
tags:
- java


方法參數介紹

一個方法不能修改一個基本數據類型的參數(即數值型和布爾型)

一個方法可以改變一個對象參數的狀態

一個方法不能讓對象參數引用一個新的對象

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

java中參數的…

…表示的是可變長參數,相當於一個數組

如果是是形參 裏面出現,表示的是可變參數
比如:
//表示的傳入的參數可以隨意,你傳多少個參數都被放到一個數組裏面。
public static void dealArray(int...intArray) {
for(int i: intArray)
{
System.out.print(i +" ");
}
System.out.println();
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章