|
Re: Parameters in Java
|
Posted: Mar 17, 2002 9:55 AM
|
|
> Parameters in Java are always passed by value yet a > method call cause the attributes of an oject > parameter to be updated.Why is this?
Let us take an example. yourobjectreference yor = new yourobject() ;
aMethod ( yor ) ;
By saying, all parameters are passed by value in Java, we are saying that the reference to your object, which is yor, is passed by value to the method aMethod. Here, we are not passing the object itself, rather a reference to the object. Since, yor is passed by value to aMethod, even if we set yor to some other object within aMethod our original reference yor doesn't change. It still refers to the original object. However, the copy of yor is passed to aMethod and this copy also is a reference to the same object which yor is refering to. Since, yor and the copy of yor inside aMethod, both are reference to the same object they are capable of affecting the object in same way. So, inside aMethod you can change the object. For example,
yourobjectreference yor = object1 ;
aMethod ( yourobjectreference yorCopy ) {
// Here yorCopy also refers to object1.
// However, yorCopy is a copy of yor and
// it is because parameters are passed by value
// in Java. Since yorCopy also refers to object1
// you can change object1, if you really can, using
// methods and properties of objects1.
// Important thing is if you say,
yorCopy = object2 ;
// Then only yorCopy is now refering to object2
// and yor is still refering to object1. This is
// what we mean by saying that all parameters
// are passed by value in java
}
Thanks Kishori
|
|