phone: 016-6933793
e-mail: darknessofsorrow@hotmail.com

Sunday, 21 October 2012

Constructors

A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object. Its can be used to initialize the objects to required, or default values at the time of objects creation. It is not mandatory for the coder to write a constructor for the class.

Rules for constructors :

  1. The constructor has the same class as the class.
  2. The only output argument from a constructor is the object constructed.
  3. The constructor can return only a single argument.
  4. Constructors must always return a valid instance of the class. Never return an empty object from a class constructor.
  5. If constructor makes an explicit call to a superclass constructor, this call must occur before any other reference to the constructed object.


Constructors often have multiple definitions, each with different numbers or types of parameters, and they sometimes parallel a class's set methods. As an example, Figure 1 contains a definition of our class Pet that includes several constructors. Note that the headings of these constructors do not have the word void. When define a constructor, do not specify any return type, not even void. These constructors look very much like our set methods, which are void methods. In fact, we have grouped each constructor with its similar set method, just for this example. 

Figure 1 : Class Diagram for a Class Pet




0 comments: