Referring to the Current Objects Members with the this Reference

Referring to the Current Object s Members with the this Reference

Every object can access a reference to itself with keyword this (sometimes called the this reference). When a non-static method is called for a particular object, the method's body implicitly uses keyword this to refer to the object's instance variables and other methods. As you will see in Fig. 8.4, you can also use keyword this explicitly in a non-static method's body. Section 8.5 shows another interesting use of keyword this. Section 8.11 explains why keyword this cannot be used in a static method.

Figure 8.4. this used implicitly and explicitly to refer to members of an object.

(This item is displayed on pages 364 - 365 in the print version)

 1 // Fig. 8.4: ThisTest.java
 2 // this used implicitly and explicitly to refer to members of an object.
 3
 4 public class ThisTest
 5 {
 6 public static void main( String args[] )
 7 {
 8 SimpleTime time = new SimpleTime( 15, 30, 19 );
 9 System.out.println( time.buildString() );
10 } // end main
11 } // end class ThisTest
12
13 // class SimpleTime demonstrates the "this" reference
14 class SimpleTime
15 {
16 private int hour; // 0-23
17 private int minute; // 0-59
18 private int second; // 0-59
19
20 // if the constructor uses parameter names identical to
21 // instance variable names the "this" reference is
22 // required to distinguish between names
23 public SimpleTime( int hour, int minute, int second )
24 {
25 this.hour = hour; // set "this" object's hour 
26 this.minute = minute; // set "this" object's minute
27 this.second = second; // set "this" object's second
28 } // end SimpleTime constructor
29
30 // use explicit and implicit "this" to call toUniversalString
31 public String buildString()
32 {
33 return String.format( "%24s: %s
%24s: %s",
34 "this.toUniversalString()", this.toUniversalString(),
35 "toUniversalString()", toUniversalString() );
36 } // end method buildString
37
38 // convert to String in universal-time format (HH:MM:SS)
39 public String toUniversalString()
40 {
41 // "this" is not required here to access instance variables,
42 // because method does not have local variables with same
43 // names as instance variables
44 return String.format( "%02d:%02d:%02d",
45 this.hour, this.minute, this.second );
46 } // end method toUniversalString
47 } // end class SimpleTime
 
this.toUniversalString(): 15:30:19
 toUniversalString(): 15:30:19
 

We now demonstrate implicit and explicit use of the this reference to enable class ThisTest's main method to display the private data of a class SimpleTime object (Fig. 8.4). Note that this example is the first in which we declare two classes in one fileclass ThisTest is declared in lines 411, and class SimpleTime is declared in lines 1447. We did this to demonstrate that when you compile a .java file that contains more than one class, the compiler produces a separate class file with the .class extension for every compiled class. In this case two separate files are producedone for SimpleTime and one for ThisTest. When one source-code (.java) file contains multiple class declarations, the class files for those classes are placed in the same directory by the compiler. Also, note that only class ThisTest is declared public in Fig. 8.4. A source-code file can contain only one public classotherwise, a compilation error occurs.

Class SimpleTime (lines 1447) declares three private instance variableshour, minute and second (lines 1618). The constructor (lines 2328) receives three int arguments to initialize a SimpleTime object. Note that we used parameter names for the constructor (line 23) that are identical to the class's instance variable names (lines 1618). We don't recommend this practice, but we did it here to shadow (hide) the corresponding instance variables so that we could illustrate explicit use of the this reference. If a method contains a local variable with the same name as a field, that method will refer to the local variable rather than the field. In this case, the local variable shadows the field in the method's scope. However, the method can use the this reference to refer to the shadowed field explicitly, as shown in lines 2527 for SimpleTime's shadowed instance variables.

Method buildString (lines 3136) returns a String created by a statement that uses the this reference explicitly and implicitly. Line 34 uses the this reference explicitly to call method toUniversalString. Line 35 uses the this reference implicitly to call the same method. Note that both lines perform the same task. Programmers typically do not use this explicitly to reference other methods within the current object. Also, note that line 45 in method toUniversalString explicitly uses the this reference to access each instance variable. This is not necessary here, because the method does not have any local variables that shadow the instance variables of the class.

Common Programming Error 8.2

It is often a logic error when a method contains a parameter or local variable that has the same name as a field of the class. In this case, use reference this if you wish to access the field of the classotherwise, the method parameter or local variable will be referenced.

Error-Prevention Tip 8.1

Avoid method parameter names or local variable names that conflict with field names. This helps prevent subtle, hard-to-locate bugs.

Application class ThisTest (lines 411) demonstrates class SimpleTime. Line 8 creates an instance of class SimpleTime and invokes its constructor. Line 9 invokes the object's buildString method, then displays the results.

Performance Tip 8.1

Java conserves storage by maintaining only one copy of each method per classthis method is invoked by every object of the class. Each object, on the other hand, has its own copy of the class's instance variables (i.e., non-static fields). Each method of the class implicitly uses this to determine the specific object of the class to manipulate.


Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

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