Jump to content

Constructor function

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Hadal (talk | contribs) at 21:25, 25 March 2004 (bolding, reorder sentence). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computer programming, a constructor function is a member function of a class and always has the same name as the class.

It is used to create an object instance of a particular class and possibly also populate some or all of that object instance's attributes.

A class may have more than one constructor function allowing multiple ways to create an object instance, as in example 2 below, an account can be created without supplying an initial balance and one where an initial balance can be supplied in the call to the constructor function.

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 );
       }

}