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