专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java参数传递的方法及示例

Java参数传递的方法及示例

更新时间:2022-04-19 09:53:48 来源:赢咖4 浏览1124次

赢咖4小编来给大家举几个Java参数传递的示例。

参数传递的重要方法

1.按值传递:

对形式参数所做的更改不会传回给调用者。任何对被调用函数或方法内部形参变量的修改只影响单独的存储位置,不会反映在调用环境中的实参中。此方法也称为按值调用。Java 实际上是严格按值调用的。

例子:

// Java program to illustrate
// Call by Value
// Callee
class CallByValue {
	// Function to change the value
	// of the parameters
	public static void Example(int x, int y)
	{
		x++;
		y++;
	}
}
// Caller
public class Main {
	public static void main(String[] args)
	{
		int a = 10;
		int b = 20;
		// Instance of class is created
		CallByValue object = new CallByValue();
		System.out.println("Value of a: " + a
						+ " & b: " + b);
		// Passing variables in the class function
		object.Example(a, b);
		// Displaying values after
		// calling the function
		System.out.println("Value of a: "
						+ a + " & b: " + b);
	}
}

输出:

a的值:10 & b:20
a的值:10 & b:20

缺点:

存储分配效率低下

对于对象和数组,复制语义代价高昂

2.通过引用调用(别名):

对形式参数所做的更改确实会通过参数传递传递回调用者。对形式参数的任何更改都会反映在调用环境中的实际参数中,因为形式参数接收到对实际数据的引用(或指针)。此方法也称为引用调用。这种方法在时间和空间上都是有效的。

例子:

// Java program to illustrate
// Call by Reference
// Callee
class CallByReference {
	int a, b;
	// Function to assign the value
	// to the class variables
	CallByReference(int x, int y)
	{
		a = x;
		b = y;
	}
	// Changing the values of class variables
	void ChangeValue(CallByReference obj)
	{
		obj.a += 10;
		obj.b += 20;
	}
}
// Caller
public class Main {
	public static void main(String[] args)
	{
		// Instance of class is created
		// and value is assigned using constructor
		CallByReference object
			= new CallByReference(10, 20);
		System.out.println("Value of a: "
						+ object.a
						+ " & b: "
						+ object.b);
		// Changing values in class function
		object.ChangeValue(object);
		// Displaying values
		// after calling the function
		System.out.println("Value of a: "
						+ object.a
						+ " & b: "
						+ object.b);
	}
}

输出:

a的值:10 & b:20
a的值:20 & b:40

请注意,当我们传递一个引用时,会为同一个对象创建一个新的引用变量。所以我们只能改变传递引用的对象的成员。我们不能更改引用以引用其他对象,因为接收到的引用是原始引用的副本。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>