Information Technology Reference
In-Depth Information
Putting It All Together
The following code creates two instances and stores their references in variables named T1 and
T2 . Figure 4-8 illustrates T1 and T2 in memory. The code demonstrates the following three
actions discussed so far in the use of a class:
￿
Declaring a class
￿
Creating instances of the class
￿
Accessing the class members (i.e., writing to a field and reading from a field)
class DaysTemp // Declare the class.
{
public int High, Low; // Declare the instance fields.
public int Avg() // Declare the instance method.
{
return (High + Low) / 2;
}
}
class Class1
{
static void Main()
{
DaysTemp T1 = new DaysTemp();
// Create 2 instances of DaysTemp.
DaysTemp T2 = new DaysTemp();
// Write to the fields of each instance.
T1.High = 76; T1.Low = 57;
T2.High = 75; T2.Low = 53;
// Read from the fields of each instance and call a method of
// each instance.
Console.WriteLine("T1: {0}, {1}, {2}", T1.High, T1.Low, T1.Avg ());
Console.WriteLine("T2: {0}, {1}, {2}", T2.High, T2.Low, T2.Avg ());
} Field Field Method
}
Search WWH ::




Custom Search