Chapter 8 Object-Based (Web site templates) Programming 309 1 // Fig.
Thursday, November 1st, 2007Chapter 8 Object-Based Programming 309 1 // Fig. 8.10: CompositionTest.cs 2 // Demonstrate an object with member object reference. 3 4 using System; 5 using System.Windows.Forms; 6 7 // Composition class definition 8 class CompositionTest 9 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 Employee e = 14 new Employee( “Bob”, “Jones”, 7, 24, 1949, 3, 12, 1988 ); 15 16 MessageBox.Show( e.ToEmployeeString(), 17 “Testing Class Employee” ); 18 19 } // end method Main 20 21 } // end class CompositionTest Fig. 8.10 Fig. 8.10Fig. 8.FiFi10g. 8.10g. 8.10Composition demonstration. 8.9 Using the thisReference Every object can access a reference to itself, called the this reference. The this reference can refer implicitly to the instance variables, properties and methods of an object. Keyword thisis commonly used within methods, where thisis a reference to the object on which the method is performing operations. In the Windows application of Fig. 6.4, there are several uses of this in method InitializeComponent. The application uses the this keyword to reference the form that is being initialized. Every form has an InitializeComponent methods, so the thisreference provides us with an easy way to access the information in the current object. Additional examples of this appear in Chapters 12 and 13. We now demonstrate implicit and explicit use of the thisreference to display the private data of a Time4 object. Class Time4 (Fig. 8.11) defines three private instance variables hour, minute and second (lines 9 11). The constructor (lines 14 19) receives three int arguments to initialize a Time4 object. Note that, for this example, we have made the parameter names for the constructor (line 14) identical to the instance variable names for the class (lines 9 11). We did this to illustrate explicit use of the thisreference. If a method contains a local variable with the same name as an instance variable of that class, that method will refer to the local variable, rather than to the instance variable (i.e., the local variable hides the instance variable in that method s scope). However, the method can use the thisreference to refer to the hidden instance variables explicitly (lines 16 18).
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.