Reference primitive call by XXX TAHO In java
Reference, primitive, call by XXX 必也正名乎 誌謝: 部份文字取於前輩TAHO的文章
In java, there are two types… • Primitive types and Reference types • 這兩種 Type 限制了 variable 所能握有(hold) 的 value 種類
Recall that… obj. Ref 1=0 x 3200 obj. Ref 2=0 x 4650 heap obj. Ref 3=0 x 3288 (Reference type variables) int. Value=3 boolean. Value=true (Primitive type variables) (Object instances inside)
Type, variable, value • 當 variable hold 的是 primitive value 時,我 們稱這個 variable 是 primitive type 的變數 • 反之 當 variable hold 的是 reference value 時, 我們稱這個 variable 是 reference type 的變 數 – 這句話是說 它是個 "參考型別的變數",而非 " 它是個參考"
所謂call by value void m 1 (Person p) { p = null; } //some other place Person person. Obj = new Person(“John”); m 1(person. Obj); • 把person. Obj中所存的reference value (一個數值),當 做參數傳給m 1 • 在m 1當中,把p變成null,並不會對實體物件有動作, 只是把p所儲存的值清掉 – 影響的範圍,只在m 1中而已
Discussion • Java是call by value還是call by reference – 對primitive types而言,call by value – 對reference types而言,call by “reference” value • 其實也是 call by value,只是這個value是記憶體位置的值 – 所以,java只有call by value (官方文件也是如此說) – 與 C 語言同理 • 逼免造成混亂,最好不要誤用 reference, alias 等名詞,因為在不同的程式語言有不同涵意
In C++ Primer • "A reference is an Alias" – "Because a reference is just another name for the object to which it is bound, all operations on a reference are actually operations on the underlying object to which the reference is bound. " – (此處object代表東西,不是我們一般Java認知的物 件) • X = NULL,你是把X裡頭的值變NULL,還是把X 所指向的物件變成NULL? – 問題的關鍵在於”你到底在對誰動作”
- Slides: 12