Java Reference
In-Depth Information
continued
static void changeString(String s) {
s = new String("b");
}
public static void main(String[] args) {
Test t = new Test();
System.out.println("a is: "+t.a);
Test.changeString(t.a);
System.out.println("a is now: "+t.a);
}
}
As such, modifying the argument variable s will cause a new String object to
be created, which will also cause the address referenced to by that variable to
change, and be different from the original address in t.a .
One interesting remark to make in this context is about final variables. As you have seen, instance
variables and local variables can be declared as being final to prevent multiple initializations.
Parameter variables can also be final, meaning that it's possible to write a method like so:
class Test {
void editNames(final String[] argNames) {
// Will not work due to final modifier:
// argNames = new String[]{"Caesar"};
// This will work:
argNames[0] = "Caesar";
}
}
This completely corresponds with the definition of final variables as explained before, keeping in
mind that finalizing a variable is not the same as “freezing” it completely, but it does prevent new
initializations. However, since argNames will be discarded once the method is exited, why would
you even bother to declare a parameter variable as final? One particularly straightforward reason
is to prevent you from accidentally re‐initializing the variable, to prevent you from overwriting the
address stored on a variable's piece of paper with a new one. When you actually want methods to
directly modify an object, you in fact want to avoid creating a new object, as the address referenced
by the argument will then change and be discarded once you exit the method. Using final helps
prevent such mistakes.
This concludes the overview on beginning object‐oriented programming in Java. You have covered
a lot of ground. You have seen how to define classes, with data being represented by instance and
class variables—final or not—and behavior being represented by instance and class methods. You
have also seen how to define class constructors, and read about the special main method to execute
your programs.
Search WWH ::




Custom Search