Constructor function

A constructor function, in computer programming, 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 instance of 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 );

        }
}
Navigation

<MenuNavigation7>

Toolbox
Personal tools