Constructor (computer science)


Constructor (computer science)

In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special block of statements called when an object is created, either when it is declared (statically constructed on the stack, possible in C++ but not in Java and other object-oriented languages) or dynamically constructed on the heap through the keyword “new”.

A constructor is similar to an instance method, but it differs from a method in that it never has an explicit return type, it's not inherited, and usually has different rules for scope modifiers. Constructors are often distinguished by having the same name as the declaring class. Their responsibility is to initialize the object's data members and to establish the invariant of the class, failing if the invariant isn't valid. A properly written constructor will leave the object in a 'valid' state. Immutable objects must be initialized in a constructor.

The term "constructor" is also used to denote one of the tags that wraps data in an algebraic data type. This is a different usage than in this article. For more information, see algebraic data type.

In most languages, the constructor can be overloaded in that there can be more than one constructor for a class, each having different parameters. Some languages take consideration of some special types of constructors:
* default constructor - a constructor that can take no arguments
* copy constructor - a constructor that takes one argument of the type of the class (or a reference thereof)


= Java =

Some of the differences between constructors and other Java methods:

*Constructors never have an explicit return type.
*Constructors cannot be directly invoked (the keyword “new” must be used).
*Constructors cannot be synchronized, final, abstract, native, nor static.
*Constructors are always executed by the same thread.

Apart from this java constructor's performs the following functions in the said order.
1) Initializes the class variables to default values i.e byte,short,int,long or char variable to 0,float variable to 0.0f, double variable to 0.0, boolean variable to false and references of any objects to null.
2) It then calls the super class constructor (default constructor of super class only if no constructor is defined).
3) It then initializes the class variables to the specified values like ex: int var = 10; or float var = 10.0f and so on.
4) It then executes the body of the constructor.

Example

public class Example { //definition of the constructor. public Example() { this(1); }

//overloading a constructor public Example(int input) { data = input; }

//declaration of instance variable(s). private int data;}

//code somewhere else//instantiating an object with the above constructorExample e = new Example(42);

Visual Basic .NET

Constructors in Visual Basic use a method declaration with the name "New".

Example

Class Foobar Private strData As String ' Constructor Public Sub New(ByVal someParam As String) strData = someParam End SubEnd Class

' code somewhere else' instantiating an object with the above constructorDim foo As New Foobar(".NET")


= C# =

Example

class myClass{ private int mA; private string mB;

public myClass(int a, string b) { mA = a; mB = b;

//code somewhere//instantiating an object with the constructor abovemyClass c = new myClass(42, "string");

ColdFusion

Example

It's important to note that there is no constructor method in ColdFusion. A common practice among developers in the ColdFusion community is to create an 'init' method that acts as a pseudo-constructor.

PHP

Example

In PHP (Version 5 and above) the constructor is a method named __construct(), which is automatically called by the keyword new after creating the object. It is usually used to automatically perform various initializations such as property initializations. Constructors can also accept arguments, inwhich case, when the new statement is written, you also need to send the constructor the function parameters in between the parentheses.

class Person{ private $name;

function __construct($name) { $this->name = $name; } function getName() { return $this->name;

However, constructor in PHP version 4 (and earlier) is a method in a class with the same name of the class.

class Person{ private $name;

function Person($name) { $this->name = $name; } function getName() { return $this->name;

Constructors simplified (with pseudocode)

Constructors are always part of the implementation of classes. A class (in programming) refers to a specification of the general characteristics of the set of objects that are members of the class rather than the specific characteristics of any object at all. A simple analogy follows. Consider the set (or class, using its generic meaning) of students at some school. Thus we have

class Student { // refers to the class of students // ... more omitted ...}

However, the class Student is just a generic prototype of what a student should be. To use it, the programmer creates each student as an "object" or "instance" of the class. This object is a real quantity of data in memory whose size, layout, characteristics, and (to some extent) behavior are determined by the class definition. The usual way of creating objects is to call a constructor (classes may in general have many independent constructors). For example,

class Student { Student (String studentName, String Address, int ID) { // ... storage of input data and other internal fields here ... } // ...}

ee also

*Destructor


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Object (computer science) — In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure. (With the later introduction of object oriented programming the same word,… …   Wikipedia

  • String (computer science) — In formal languages, which are used in mathematical logic and theoretical computer science, a string is a finite sequence of symbols that are chosen from a set or alphabet. In computer programming, a string is traditionally a sequence of… …   Wikipedia

  • Polymorphism (computer science) — This article is about the programming language theory concepts with direct application to functional programming languages. For a gentler introduction of these notions as commonly implemented in object oriented programming, see Polymorphism in… …   Wikipedia

  • Reference (computer science) — This article is about a general notion of reference in computing. For the more specific notion of reference used in C++, see Reference (C++). In computer science, a reference is a value that enables a program to indirectly access a particular… …   Wikipedia

  • Union (computer science) — In computer science, a union is a data structure that stores one of several types of data at a single location. There are only two safe ways of accessing a union object. One is to always read the field of a union most recently assigned; tagged… …   Wikipedia

  • Unification (computer science) — Unification, in computer science and logic, is an algorithmic process by which one attempts to solve the satisfiability problem. The goal of unification is to find a substitution which demonstrates that two seemingly different terms are in fact… …   Wikipedia

  • Integer (computer science) — In computer science, an integer is a datum of integral data type, a data type which represents some finite subset of the mathematical integers. Integral data types may be of different sizes and may or may not be allowed to contain negative values …   Wikipedia

  • Class (computer science) — In object oriented programming, a class is a programming language construct that is used as a blueprint to create objects. This blueprint includes attributes and methods that the created objects all share.More technically, a class is a cohesive… …   Wikipedia

  • Swap (computer science) — For other uses of swap , see swap (disambiguation). In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program,… …   Wikipedia

  • Method (computer science) — In object oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods, static methods, or factory methods) or with an object (called instance methods). Like a procedure in… …   Wikipedia