更新時(shí)間:2022-04-19 09:53:48 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1596次
動(dòng)力節(jié)點(diǎn)小編來(lái)給大家舉幾個(gè)Java參數(shù)傳遞的示例。
1.按值傳遞:
對(duì)形式參數(shù)所做的更改不會(huì)傳回給調(diào)用者。任何對(duì)被調(diào)用函數(shù)或方法內(nèi)部形參變量的修改只影響單獨(dú)的存儲(chǔ)位置,不會(huì)反映在調(diào)用環(huán)境中的實(shí)參中。此方法也稱(chēng)為按值調(diào)用。Java 實(shí)際上是嚴(yán)格按值調(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
缺點(diǎn):
存儲(chǔ)分配效率低下
對(duì)于對(duì)象和數(shù)組,復(fù)制語(yǔ)義代價(jià)高昂
2.通過(guò)引用調(diào)用(別名):
對(duì)形式參數(shù)所做的更改確實(shí)會(huì)通過(guò)參數(shù)傳遞傳遞回調(diào)用者。對(duì)形式參數(shù)的任何更改都會(huì)反映在調(diào)用環(huán)境中的實(shí)際參數(shù)中,因?yàn)樾问絽?shù)接收到對(duì)實(shí)際數(shù)據(jù)的引用(或指針)。此方法也稱(chēng)為引用調(diào)用。這種方法在時(shí)間和空間上都是有效的。
例子:
// 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
請(qǐng)注意,當(dāng)我們傳遞一個(gè)引用時(shí),會(huì)為同一個(gè)對(duì)象創(chuàng)建一個(gè)新的引用變量。所以我們只能改變傳遞引用的對(duì)象的成員。我們不能更改引用以引用其他對(duì)象,因?yàn)榻邮盏降囊檬窃家玫母北尽?/p>
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)