changing address of object in Java (pass
Before I post my question, I have read the following excellent articles on java-pass-by-value. I am convinced I have understood it well.
My question has to do with a side-by comparison of Java with other language that supports pass-by-reference
( C++
may be).
In case of Java
, you have a handle (reference) pointing to the object in location A. so object itself could be modified. But It is not possible to change the object location itself. Ie An object stored in memory address 0X945 cannot be changed to 0X948.
In languages such as C++
, you can choose to pass-by-value
or pass-by-reference
. (It is in the hands of the programmer correct?). Hence it is possible to change the location of object in memory space correct?
PS: I have good background on Java but on C++. so my views above may be wrong. It is claimed in the article 1, I cited above that there is no notion of pointers in Java. I dont know how far that is true? (why do NullPointerException
exists then)
EDIT: consider this example:
void swap(Object A,Object B) {
Object temp=B;
Object B=A;
Oject A=temp;
}
when I call the method in Java such as swap(A,B)
, nothing happens but in C++ (I presume), swap happens. which probably means I am changing the location of objects in memory correct?
In java even - references to objects are passed by value. ie, everything is pass-by-value. Next,
you can choose to pass-by-value or pass-by-reference. (It is in the hands of the programmer correct?). Correct. But you can't do it in Java.
An object stored in memory address 0X945 cannot be changed to 0X948. You can't do this in both java and C++.
NullPointerException
is thrown when you try to access a property / method of something which doesn't exist (is null
). ie, the reference points to null
when an instance of the object is required.
Object o = null;
o.toString() --> NPE. o points to null.
so in C++, do pass-by-reference means you pass the object itself, so that it could be reassigned in swap method
In C++, pass by reference, swap(Object &A, Object &B)
appears to be close to java's pass by value.
In Java Object A
is a reference to an Object and is null
by default. As Object
is already a reference and so when this reference is copied, it is passed by value.
In C++, Object A
is an instance of an Object and is always a unique object. As Object
is an instance, you are passing by reference using Object&
because the Object
is not passed, but a reference to it.
Java总是按值传递,就是当你传递对象时,传递的值是内存中的位置,所以它可以像传递引用一样行事。
链接地址: http://www.djcxy.com/p/20670.html上一篇: C#变量范围阻止了我的脚步
下一篇: 改变Java中对象的地址(pass