In below example you can see how object is passed to the method.
Objects in Java are passed by reference (or value of the reference). Objects are stored on the heap.
Primitive types in Java are passed by value and they are stored on the stack.
package p_2013_04_03; class Dog { public String name; public Dog( String aName ) { this.name = aName; } public void getName() { System.out.println(this.name); } public void setName( String aName ) { this.name = aName; } } public class Reference { public static void main(String[] args) { Dog myDog = new Dog("Raff"); myDog.getName(); Reference ref = new Reference(); ref.foo(myDog); // changing name for "Rex" in foo method // "myDog" have got new name = "Rex". NOT "Max" myDog.getName(); } // object is passed by reference (value of reference is passed to function) public void foo( Dog aSomeDog ) { // reference to "myDog" aSomeDog.getName(); aSomeDog.setName("Rex"); // assigning new reference to object "aSomeDog" (NOT "myDog"!!!) aSomeDog = new Dog("Max"); aSomeDog.getName(); } }
As you can see reference to "myDog" named Raff was passed to the foo method.
Now we have got two references to the "myDog" object.
Then we changed named from Raff to Rex.
After that we have assign new object to the given reference and we have changed name to Max - but name of "myDog" wasn't changed because that reference doesn't point longer at the "myDog" object.
No comments:
Post a Comment