Java Reference
In-Depth Information
public static void main(String[]args){
i
int i = 10;
...
int x = obj.change(i);
...
10
copy of i
}
10
j refers to the
copy
acts on
int change( int j){
This statement
modifies the copy,
not the original
++j;
return j;
}
This just means that for each argument value that you pass to a method, a copy is made, and it is the
copy that is passed to the method and referenced through the parameter name, not the original value.
This implies that if you use a variable of any of the basic types as an argument, the method cannot
modify the value of this variable in the calling program. In the example shown, the method change()
will modify the copy of i that is created automatically, so the value of j that is returned will be 11 and
this will be stored in x . However, the original value of i will remain at 10.
While the pass-by-value mechanism applies to all types of arguments, the effect for
objects is different from that for variables of the basic types. You can change an
object, as we shall see a little later in this chapter, because a copy of a reference to the
object is passed to the method, not a copy of the object itself.
Final Parameters
You can specify any method parameter as final . This has the effect of preventing modification of any
argument value that is substituted for the parameter when you call the method. The compiler will check
that your code in the body of the method does not attempt to change any final parameters. Since the
pass-by-value mechanism makes copies of values of the basic types, final really only makes sense
when it is applied to parameters that are references to class objects, as we will see later on.
Specifying a parameter of a class as final is of limited value. It does prevent accidental modification of the
object reference that is passed to the method, but it does not prevent modification of the object itself.
Defining Class Methods
You define a class method by adding the keyword static to its definition. For example, the class
Sphere could have a class method to return the value stored in the static variable, count :
class Sphere {
// Class definition as before...
Search WWH ::




Custom Search