更新時間:2022-04-19 09:53:48 來源:動力節點 瀏覽1523次
動力節點小編來給大家舉幾個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
請注意,當我們傳遞一個引用時,會為同一個對象創建一個新的引用變量。所以我們只能改變傳遞引用的對象的成員。我們不能更改引用以引用其他對象,因為接收到的引用是原始引用的副本。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習