7.12. The this Keyword

 
[Page 236]

7.12. The this Keyword

Sometimes you need to reference a class's hidden variable in a method. For example, a property name is often used as the parameter name in a set method for the property. In this case, you need to reference the hidden property name in the method in order to set a new value to it. A hidden static variable can be accessed simply by using the ClassName.StaticVariable reference. A hidden instance variable can be accessed by using the keyword this , as shown in Figure 7.19(a).

Figure 7.19. The keyword this serves as the proxy for the object that invokes the method.

The line this.i = i means "assign the value of parameter i to the data field i of the calling object." The keyword this serves as a proxy for the object that invokes the instance method setI , as shown in Figure 7.19(b). The line Foo.k = k means that the value in parameter k is assigned to the static data field k of the class, which is shared by all the objects of the class.

The keyword this can also be used inside a constructor to invoke another constructor of the same class. For example, you can redefine the Circle class as follows :

The line this(1.0) invokes the constructor with a double value argument in the class.

Tip

If a class has multiple constructors, it is better to implement them using this(arg-list) as much as possible. In general, a constructor with no or fewer arguments can invoke the constructor with more arguments using this(arg-list) . This often simplifies coding and makes the class easier to read and to maintain.



[Page 237]

Note

Java requires that the this(arg-list) statement appear first in the constructor before any other statements.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

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