Jump to content

Constructor function

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by The Rambling Man (talk | contribs) at 11:39, 31 August 2005 (Categorised). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A constructor function, in computer programming, is a member function of a class used to create an object instance of a particular class and possibly also populate some or all of that object instance's attributes. In some languages, particularly those derived from C++, a constructor is a method with the same name as its class; in others, it is a method with a specific reserved name such as "init", "New", or "Constructor".

In languages which support method overloading, a class may have more than one constructor function, thereby allowing multiple ways to create an object instance. In example 2 below, an instance of an account can be created with or without an initial balance.

Example 1. (In JavaScript)

 // constructor function
 function MyObject(attributeA, attributeB) 
 {
   this.attributeA = attributeA
   this.attributeB = attributeB
 }

 // create an Object
 obj = new MyObject('red', 1000)

Example 2. (In Java)

public class Account 
{
        protected double balance;

        // Constructor function        
        public Account()
	{
               balance = 0.0;
	}


        // Constructor function to initialize balance
        public Account( double amount )
	{
		balance = amount;
	}

        public double getbalance()
	{
                return balance;
	}
}  

public class AccountTester
{
        public static void main( String args[] )
        { 
           // Create an empty account
           Account acc1 = new Account();

           // Create an account with a balance
           Account acc2 = new Account( 5000.0 );

        }
}