Constructor function |
A constructor function, in computer programming, is a member function of a Class (computer science) used to create an object (computer science) 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 programming language)
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 );
} }|
|