This is an old revision of this page, as edited by Beno1000 (talk | contribs) at 07:04, 16 January 2010. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Revision as of 07:04, 16 January 2010 by Beno1000 (talk | contribs)(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff) ShortcutsIn object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a special type of subroutine 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 when it is dynamically constructed on the heap through the keyword "new
". Its purpose is to prepare the new object for use, often accepting parameters which are used by the constructor to set member variables which are required when the object is first created.
A constructor is similar to an instance method, but it differs from a method in that it never has an explicit return type, it is 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, a java constructor performs the following functions in the said order.
- It initializes the class variables to default values. (Byte, short, int, long, float, and double variables default to their respective zero values, booleans to false, chars to the null character ('\u0000') and references of any objects to null.)
- It then calls the super class constructor (default constructor of super class only if no constructor is defined).
- It then initializes the class variables to the specified values like ex: int var = 10; or float var = 10.0f and so on.
- 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 constructor Example 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 Sub End Class
' code somewhere else ' instantiating an object with the above constructor Dim foo As New Foobar(".NET")
C#
Example
public class MyClass { private int a; private string b; //constructor public MyClass(int a, string b) { this.a = a; this.b = b; } }
//code somewhere //instantiating an object with the constructor above MyClass c = new MyClass(42, "string");
C# Static Constructor
A static constructor in C# is a static data initializer. Static constructors allow complex static variable initialization. Static constructors can be called once and call is made implicitly by the run-time right before the first time the class is being accessed. Any call to a class (static or constructor call), triggers the static constructor execution. Static constructors are thread safe and are a great way to implement a Singleton pattern. When used in a Generic programming class, static constructors are called on every new generic instantiation one per type (static variables are instantiated as well).
Static Constructor Example
public class MyClass { private static int _A; //normal constructor static MyClass() { _A = 32; } //standard default constructor public MyClass() { } }
//code somewhere //instantiating an object with the constructor above //right before the instantiation //the variable static constructor is executed and _A is 32 MyClass c = new MyClass();
F#
A constructor in F# is composed of any let
or do
statements defined in a class. let
statements define private fields and do
statements execute code. Additional constructors can be defined using the new
keyword.
Example
type MyClass(_a : int, _b : string) = class // primary constructor let a = _a let b = _b do printfn "a = %i, b = %s" a b // additional constructors new(_a : int) = MyClass(_a, "") then printfn "Integer parameter given" new(_b : string) = MyClass(0, _b) then printfn "String parameter given" new() = MyClass(0, "") then printfn "No parameter given" end
//code somewhere //instantiating an object with the primary constructor let c1 = new MyClass(42, "string") //instantiating an object with additional constructors let c2 = new MyClass(42) let c3 = new MyClass("string") let c4 = MyClass() // "new" keyword is optional
Eiffel
In Eiffel, the routines which initialize new objects are called creation procedures. Creation procedures are similar to constructors in some ways and different in others. Creation procedures have the following characteristics:
- Creation procedures never have an explicit return type (by definition of procedure).
- Creation procedures are named. Names are restricted only to valid identifiers.
- Creation procedures are designated by name as creation procedures in the text of the class.
- Creation procedures can be directly invoked to re-initialize existing objects.
- Every effective (i.e., concrete or non-abstract) class must designate at least one creation procedure.
- Creation procedures are responsible for leaving the newly initialized object in a state that satisfies the class invariant.
Although object creation is subject some subtleties, the creation of an attribute with a typical declaration x: T
as expressed in a creation instruction create x.make
consists of the following sequence of steps:
- Create a new direct instance of type
T
. - Execute the creation procedure
make
to the newly created instance. - Attach the newly initialized object to the entity
x
.
Example
In the first snippet below, class POINT
is defined. The procedure make
is coded after the keyword feature
.
The keyword create
introduces a list of procedures which can be used to initialize instances. In this case the list includes default_create
, a procedure with an empty implementation inherited from class ANY
, and the make
procedure coded within the class.
class POINT create default_create, make feature make (a_x_value: REAL; a_y_value: REAL) do x := a_x_value y := a_y_value end x: REAL -- X coordinate y: REAL -- Y coordinate ...
In the second snippet, a class which is a client to POINT
has a declarations my_point_1
and my_point_2
of type POINT
.
In procedural code, my_point_1
is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure default_create
inherited from class ANY
is used. This line could have been coded create my_point_1.default_create
.
Only procedures named as creation procedures can be used in an instruction with the create
keyword.
Next is a creation instruction for my_point_2
, providing initial values for the my_point_2
's coordinates.
The third instruction makes an ordinary instance call to the make
procedure to reinitialize the instance attached to my_point_2
with different values.
my_point_1: POINT my_point_2: POINT ... create my_point_1 create my_point_2.make (3.0, 4.0) my_point_2.make (5.0, 8.0) ...
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.
<cfcomponent displayname="Cheese"> <!--- properties ---> <cfset variables.cheeseName = "" /> <!--- pseudo-constructor ---> <cffunction name="init" returntype="Cheese"> <cfargument name="cheeseName" type="string" required="true" /> <cfset variables.cheeseName = arguments.cheeseName /> <cfreturn this /> </cffunction> </cfcomponent>
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, in
which 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; } }
Python
Constructors in Python are created by defining a __init__ method, and are called when a new instance is created by calling the class. Unlike other languages such as C++, derived classes in Python will not call their base classes' constructors; however, when a constructor is not defined the next one found in the class's Method Resolution Order will be called. Due to Python's use of duck typing, class members are frequently defined in the constructor, rather than in the class definition itself.
Example
class ExampleClass: def __init__(self, number): self.number = number print "Here is a number: %d" % self.number exampleInstance = ExampleClass(420)
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 ... } // ... }
Notes
- Eiffel routines are either procedures or functions. Procedures never have a return type. Functions always have a return type.
- Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.
- Full specification is documented in the Eiffel ISO/ECMA specification document, available online.
- The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.