Java Reference
In-Depth Information
avoid this problem by using this.test to refer to the instance variable and simply using
test to refer to the local variable, but a better solution might be to avoid the duplication
of variable names and definitions.
A more insidious example occurs when you redefine a variable in a subclass that already
occurs in a superclass. This can create subtle bugs in your code; for example, you might
call methods that are intended to change the value of an instance variable, but the wrong
variable is changed. Another bug might occur when you cast an object from one class to
another; the value of your instance variable might mysteriously change because it was
getting that value from the superclass instead of your class.
The best way to avoid this behavior is to be aware of the variables defined in the super-
class of your class. This awareness prevents you from duplicating a variable used higher
in the class hierarchy.
Passing Arguments to Methods
When you call a method with an object as a parameter, the object is passed into the body
of the method by reference. Any change made to the object inside the method will persist
outside of the method.
Keep in mind that such objects include arrays and all objects contained in arrays. When
you pass an array into a method and modify its contents, the original array is affected.
Primitive types, on the other hand, are passed by value.
The Passer class in Listing 5.3 demonstrates how this works.
LISTING 5.3
The Full Text of Passer.java
1: class Passer {
2:
3: void toUpperCase(String[] text) {
4: for (int i = 0; i < text.length; i++) {
5: text[i] = text[i].toUpperCase();
6: }
7: }
8:
9: public static void main(String[] arguments) {
10: Passer passer = new Passer();
11: passer.toUpperCase(arguments);
12: for (int i = 0; i < arguments.length; i++) {
13: System.out.print(arguments[i] + “ “);
14: }
15: System.out.println();
16: }
17: }
 
Search WWH ::




Custom Search