W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
對(duì)象引用變量在分配發(fā)生時(shí)以不同的方式工作。
例如,
Box b1 = new Box(); Box b2 = b1;
該片段執(zhí)行后, b1
和 b2
將指向相同的對(duì)象。
b1到b2的賦值沒(méi)有分配任何內(nèi)存或復(fù)制任何部分原始對(duì)象。 它簡(jiǎn)單地使b2指向與b1相同的對(duì)象。因此,通過(guò)b2對(duì)對(duì)象所做的任何更改將影響b1所引用的對(duì)象。
對(duì)b1的后續(xù)賦值將簡(jiǎn)單地從原始對(duì)象中解除b1而不影響對(duì)象或影響b2。
例如:
Box b1 = new Box(); Box b2 = b1; // ... b1 = null;
這里,b1已設(shè)置為null,但b2仍指向原始對(duì)象。
Java對(duì)象引用變量
class Box { int width; int height; int depth; } public class Main { public static void main(String args[]) { Box myBox1 = new Box(); Box myBox2 = myBox1; myBox1.width = 10; myBox2.width = 20; System.out.println("myBox1.width:" + myBox1.width); System.out.println("myBox2.width:" + myBox2.width); } }
上面的代碼生成以下結(jié)果。
當(dāng)一個(gè)參數(shù)傳遞給一個(gè)方法時(shí),它可以通過(guò)值或引用傳遞。Pass-by-Value將參數(shù)的值復(fù)制到參數(shù)中。對(duì)參數(shù)所做的更改對(duì)參數(shù)沒(méi)有影響。按引用傳遞參數(shù)傳遞對(duì)參數(shù)的引用。對(duì)參數(shù)所做的更改將影響參數(shù)。
當(dāng)一個(gè)簡(jiǎn)單的基本類型傳遞給一個(gè)方法時(shí),它是通過(guò)使用call-by-value來(lái)完成的。 對(duì)象通過(guò)使用調(diào)用引用傳遞。
以下程序使用“傳遞值"。
class Test { void change(int i, int j) { i *= 2; j /= 2; } } public class Main { public static void main(String args[]) { Test ob = new Test(); int a = 5, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.change(a, b); System.out.println("a and b after call: " + a + " " + b); } }
此程序的輸出如下所示:
在以下程序中,對(duì)象通過(guò)引用傳遞。
class Test { int a, b; Test(int i, int j) { a = i; b = j; } void meth(Test o) { o.a *= 2; o.b /= 2; } } public class Main { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } }
此程序生成以下輸出:
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: