前言: IT培训网小编来给大家举几个Java参数传递的示例。 参数传递的重要方法 1.按值传递: 对形式参数所做的更改不会传
IT培训网小编来给大家举几个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
请注意,当我们传递一个引用时,会为同一个对象创建一个新的引用变量。所以我们只能改变传递引用的对象的成员。我们不能更改引用以引用其他对象,因为接收到的引用是原始引用的副本。
文章出自:http://qh.itpxw.cn/peixun/software/2022121533.html
文章标题:Java参数传递的方法及示例
免责声明:本站文章均由入驻起航学习网的会员所发或者网络转载,所述观点仅代表作者本人,不代表起航学习网立场。如有侵权或者其他问题,请联系举报,必删。侵权投诉
IT培训网 访问该机构站点 报名留言 加为好友 用户等级:注册会员
用户级别:10
机构名称:IT培训网
联 系 人:罗老师
联系电话:13783581536
联系手机:13783581536
在线客服:
在 线 QQ:
电子邮件:
网站域名:http://www.itpxw.cn
注册时间:2016-07-18 11:07
最后登录:2024-02-20 13:02
Java定义方法的格式是什么?IT培训网小编来告诉大家。所谓方法...
大家在Java教程中会学到关于Java消息推送的知识,那么,Java消息...
常用的Java日期格式转换有哪些?IT培训网小编来告诉大家。 1...
Java创建对象数组的方法是什么?IT培训网小编来告诉大家。Ja...