Constructors


In the preceding examples, the instance variables of each Building object had to be set manually using a sequence of statements such as:

 house.occupants = 4; house.area = 2500; house.floors = 2;

An approach like this would never be used in professionally written C# code. Aside from this approach being error prone (you might forget to set one of the fields), there is simply a better way to accomplish this task: the constructor.

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. The general form of constructor is shown here:

 access class-name( ) {    // constructor code }

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object. Also, usually, access is public because constructors are normally called from outside their class.

All classes have constructors, whether you define one or not, because C# automatically provides a default constructor that initializes all member variables to zero (for value types) or null (for reference types). However, once you define your own constructor, the default constructor is no longer used.

Here is a simple example that uses a constructor:

 // A simple constructor. using System; class MyClass {   public int x;   public MyClass() {     x = 10;   } } class ConsDemo {   public static void Main() {     MyClass t1 = new MyClass();     MyClass t2 = new MyClass();     Console.WriteLine(t1.x + " " + t2.x);   } }

In this example, the constructor for MyClass is

 public MyClass() {   x = 10; }

Notice that the constructor is specified as public. This is because the constructor will be called from code defined outside of its class. This constructor assigns the instance variable x of MyClass the value 10. This constructor is called by new when an object is created. For example, in the line

 MyClass t1 = new MyClass();

the constructor MyClass( ) is called on the t1 object, giving t1.x the value 10. The same is true for t2. After construction, t2.x has the value 10. Thus, the output from the program is

 10 10

Parameterized Constructors

In the preceding example, a parameterless constructor was used. While this is fine for some situations, most often you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method: just declare them inside the parentheses after the constructor’s name. For example, here MyClass is given a parameterized constructor:

 // A parameterized constructor. using System; class MyClass {   public int x;   public MyClass(int i) {     x = i;   } } class ParmConsDemo {   public static void Main() {     MyClass t1 = new MyClass(10);     MyClass t2 = new MyClass(88);     Console.WriteLine(t1.x + " " + t2.x);   } }

The output from this program is shown here:

 10 88

In this version of the program, the MyClass( ) constructor defines one parameter called i, which is used to initialize the instance variable, x. Thus, when the line

 MyClass t1 = new MyClass(10);

executes, the value 10 is passed to i, which is then assigned to x.

Adding a Constructor to the Building Class

We can improve the Building class by adding a constructor that automatically initializes the floors, area, and occupants fields when an object is constructed. Pay special attention to how Building objects are created.

 // Add a constructor to Building. using System; class Building {   public int floors;    // number of floors   public int area;      // total square footage of building   public int occupants; // number of occupants   public Building(int f, int a, int o) {     floors = f;     area = a;     occupants = o;   }   // Display the area per person.   public int areaPerPerson() {     return area / occupants;   }   /* Return the maximum number of occupants if each      is to have at least the specified minimum area. */   public int maxOccupant(int minArea) {     return area / minArea;   } } // Use the parameterized Building constructor. class BuildingDemo {   public static void Main() {     Building house = new Building(2, 2500, 4);     Building office = new Building(3, 4200, 25);     Console.WriteLine("Maximum occupants for house if each has " +                       300 + " square feet: " +                       house.maxOccupant(300));     Console.WriteLine("Maximum occupants for office if each has " +                       300 + " square feet: " +                       office.maxOccupant(300));   } }

The output from this program is the same as for the previous version.

Both house and office were initialized by the Building( ) constructor when they were created. Each object is initialized as specified in the parameters to its constructor. For example, in the following line,

 Building house = new Building(2, 2500, 4);

the values 2, 2500, and 4 are passed to the Building( ) constructor when new creates the object. Thus, house’s copy of floors, area, and occupants will contain the values 2, 2500, and 4, respectively.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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