Constructors


When an object is created, it is given a default initial state. Fields can be set to an initial value when they are declared, or they accept the default value of their declared type. More often than not, you need more control over the initial state; the creating code would like to perform initialization routines that cannot be done with simple assignment statements.

Constructors are type members that are called to initialize an object's state before the reference is returned to the caller. They are similar to methods in that they can have zero or more arguments. Constructors do not have a return type, and they are executed after the instance state fields are assigned their initial values. Also, like methods, constructors can be overloaded.

Constructors are different from normal methods because they can only be called, implicitly, at the time the object is created. After creation, the constructor cannot be called and is not in the object's declaration space. If a class does not specify a constructor, then it will still have a default, parameterless constructor.

If your object needs to have certain values from the start, perhaps as part of a business rule, then you should not provide empty constructors.

As with other type members, it is possible to set accessibility levels on the constructor as well. Sometimes it might be desirable to have one constructor protected or internal so that derived classes or classes in the same application have one method of creating objects and have another constructor available to enforce defaults that must be set at object creation.

Another important aspect about constructors comes into play when a base class is extended. As part of object construction, the derived object can defer part of initialization to its base class. We will be covering them in much greater detail in Chapter 5.

Destructors

A constructor is called at object creation. It follows that a destructor is called when an instance is destroyed. A destructor cannot have any parameters. As such, a destructor cannot be overloaded. A class can have, at most, one destructor. Also of note, is that a destructor cannot be inherited.

C++ Note:

In C++, the programmer is virtually required to write a destructor to manage releasing memory and performing any other clean up. In Java, there is no destructor. Rather, the approach is to allow the garbage collector to handle cleanup. In C#, the best of both approaches is combined. We can rely on the Garbage Collector to manage everything related to disposing of our instance, or, we can write our own destructor, which will be called when the instance is garbage-collected.

We will cover destructors in much greater detail in Chapter 5.




C# Class Design Handbook(c) Coding Effective Classes
C# Class Design Handbook: Coding Effective Classes
ISBN: 1590592573
EAN: 2147483647
Year: N/A
Pages: 90

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