Java Reference
In-Depth Information
Forexample, we define two classes, AClass and BClass :
class AClass {
void aMethod (BClass bb) {
bb.j = 20;
}
void anotherMethod (BClass bb) {
bb = new BClass ();
bb.j = 100;
}
}
class BClass {
int j = 0;
}
In the following snippet, a reference to a BClass object is passed to aMethod()
of an AClass object. In that method, the value of bb.j is changed to 20. Since
bb inside aMethod() refers to the same object as does b in the calling code, then
b.j in the calling code takes on the value 20, losing the value 5 it originally had.
...
int i = 2;
AClass a;
BClass b;
a = new AClass ();
b = new BClass ();
b.j = 5;
a.aMethod (b);
i = b.j; // i now holds 20 not 5
...
Alternatively, look what happens when we call anotherMethod() in which
the local variable that originally held the passed reference to BClass is reassigned
to a brand new instance of BClass :
...
AClass a;
BClass b;
a = new AClass ();
b = new BClass ();
Search WWH ::




Custom Search