9.8 FINAL PARAMETERS FOR JAVA METHODS


9.8 FINAL PARAMETERS FOR JAVA METHODS

What const does for C++, final does for Java. But, for class type parameters, one has to exercise care and not push the analogy too far, as the following discussion shows.

When a parameter of a method in Java is declared to be final, its value cannot be changed inside the method. In the following example, it would be illegal to change the value of the variables x and u:

      void g(final int x, final User u) {          x = 100;                          // WRONG          u = new User();                   // WRONG      } 

But for class type parameters there is a subtle but important difference between how the qualifier const works for a parameter in C++ and how final works in Java. While the following would be unacceptable in C++

      void g(const User u) {          u.name = "Zodi";                 // WRONG      } 

Java would have no trouble with

      void g(final User u) {          u.name = "Zodi";                 // OK      } 

The reason has to do with the fact that for C++, the variable u is the User object itself, which becomes immutable if u is const. On the other hand, for the Java case the variable u is holding an immutable reference to a User object, but the object itself remains mutable. So, if the variable u is final, the object reference held by u cannot be changed. But we are free to change the object itself.

The kinds of issues we raised in the previous section-issues arising from the fact that a const argument cannot be matched with a non-const reference or pointer parameter-do not arise in Java since all arguments are passed by value. When a function parameter in Java is final, it simply means that the value of that parameter cannot be changed inside the body of the function. But there is no problem with matching a non-final argument with a final parameter.




Programming With Objects[c] A Comparative Presentation of Object-Oriented Programming With C++ and Java
Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java
ISBN: 0471268526
EAN: 2147483647
Year: 2005
Pages: 273
Authors: Avinash Kak

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net