首先,在foo(myObject)
我們正在給final
分配一些東西,它是如何可能的?
的對象不final
,在main
的可變是final
。因此,在main
中,如果您在設置其值的初始行之後添加了myObject = somethingElse;
,它將無法編譯,因爲您無法在變量中輸入新值。這對變量引用的對象是否可變是沒有影響的。
第二件事,foo()
已完成後,我們會得到myObject
是空的,所以我們怎麼能打印呢?
有兩個獨立的東西在你的代碼中調用myObject
:
中的變量main
在中foo
代碼中的參數將參數設置爲null
,但這對main
中的變量沒有任何影響。 (實際上,foo
不可能對main
中的變量產生任何影響; Java是一種純粹按值傳遞的語言,正如您所演示的,所有foo
都可以修改對象的狀態,變量和參數引用,使用傳入它的對象引用作爲參數。)
我們只是這一行foo
前停止代碼:
myObject.myInt = 1;
下面是我們在內存(留下了一些細節和不相干):
+−−−−−−−−−−−−−−−−−−−−−−+
| variable "myObject" | foo can change the
+−−−−−−−−−−−−−−−−−−−−−−+ *state* of this
foo can't change this−−>| Ref22458 |−−−+ |
+−−−−−−−−−−−−−−−−−−−−−−+ | v
| +−−−−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−+ +−−−>| object of type MyClass |
| parameter "myObject" | | +−−−−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−+ | | myInt: 2 |
foo can change this−−−−>| Ref22458 |−−−+ +−−−−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−+
...其中「 Ref22458「只是指向您在main
中創建的對象的對象引用值的名稱。
一旦我們執行在foo
兩條線:
myObject.myInt = 1;
myObject = null;
我們有這樣的記憶:
+−−−−−−−−−−−−−−−−−−−−−−+
| variable "myObject" | foo can change the
+−−−−−−−−−−−−−−−−−−−−−−+ *state* of this
foo can't change this−−>| Ref22458 |−−−+ |
+−−−−−−−−−−−−−−−−−−−−−−+ | v
| +−−−−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−+ +−−−>| object of type MyClass |
| parameter "myObject" | | +−−−−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−+ | | myInt: 1 |
foo can change this−−−−>| null |−−−+ +−−−−−−−−−−−−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−+
注意如何foo
可以改變對象的狀態(myInt
現在1
)並且可以更改參數myObject
(現在的null
)中的值,但不能更改變量myObject
(有兩個原因:它無法訪問變量[Java是按值傳遞],變量爲final
)。
因爲'myObject.myInt = 1'。你期望它是什麼? – bradimus
@bradimus它不那麼簡單......在打印語句之前將對象設置爲null,這可能會導致不熟悉Java的人員感到困惑。 –
你知道java如何將對象傳遞給另一個方法嗎? –