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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值