Witold Iwaniec wrote:
>
> I believe Java doesn't make a local copy of the method parameter, so
> uses it "by reference", but discards any changes made within this
> method.
>
> If you run Shankar's code, you can see that the changes made in fill()
> methods do not apply to the objects in main() - it is exactly what
> happens in other programs when you pass variable by value.
You are exactly opposite. Java does indeed make a local copy of any reference
you pass. When you pass a reference to a method, the method gets a copy of that
reference. That is the definition of pass by reference in Java.
It's like this:
class Dog() {
void bark() {
}
}
class TestDog {
public void fill(Dog aRef) {
aRef.bark(); //acts on dog object
aRef = new Dog(); //aRef now points to new dog
//original dog is UNCHANGED
}
public static void main {
Dog myDog = new Dog();
TestDog td = new TestDog();
td.fill(myDog);
}
}
In main() we create an instance of Dog. A reference to the dog is assigned to
the variable myDog. Think of myDog as a leash. Then we call the method fill()
with the variable myDog. Java creates another reference (leash) named aRef and
passes that to the fill() method. Both myDog and aRef refer to the same instance
of Dog. When you call a method using aRef, it acts upon the same instance of Dog
that myDog refers to. However, when you assign a new value to myRef (take the
leash off the first Dog and attach it to a new Dog) the original object is
unchanged. Likewise, the original reference, myDog, still points to the original
object.
That is why this
> public void fill(String fillMe)
> {
> fillMe = "test";
> }
does not change the String testfill. The two variables fillMe and testfill point
to the same object until you assign a new reference to fillMe. Assigning a new
value to fillMe does NOT change the value of testfill.
To change your membership options, refer to:
http://www.sys-con.com/java/list.cfm