更新時間:2022-04-19 09:53:48 來源:動力節(jié)點 瀏覽1586次
動力節(jié)點小編來給大家舉幾個Java參數(shù)傳遞的示例。
1.按值傳遞:
對形式參數(shù)所做的更改不會傳回給調(diào)用者。任何對被調(diào)用函數(shù)或方法內(nèi)部形參變量的修改只影響單獨的存儲位置,不會反映在調(diào)用環(huán)境中的實參中。此方法也稱為按值調(diào)用。Java 實際上是嚴格按值調(diào)用的。
例子:
// 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
缺點:
存儲分配效率低下
對于對象和數(shù)組,復(fù)制語義代價高昂
2.通過引用調(diào)用(別名):
對形式參數(shù)所做的更改確實會通過參數(shù)傳遞傳遞回調(diào)用者。對形式參數(shù)的任何更改都會反映在調(diào)用環(huán)境中的實際參數(shù)中,因為形式參數(shù)接收到對實際數(shù)據(jù)的引用(或指針)。此方法也稱為引用調(diào)用。這種方法在時間和空間上都是有效的。
例子:
// 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
請注意,當(dāng)我們傳遞一個引用時,會為同一個對象創(chuàng)建一個新的引用變量。所以我們只能改變傳遞引用的對象的成員。我們不能更改引用以引用其他對象,因為接收到的引用是原始引用的副本。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743