Constructor (computer science)
Encyclopedia
In object-oriented programming
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

, a constructor (sometimes shortened to ctor) in a class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

 is a special type of subroutine
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....

 called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created. It is called a constructor because it constructs the values of data members of the class.

A constructor resembles an instance method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

, but it differs from a method in that it never has an explicit return-type, it is not inherited (though many languages provide access to the superclass's constructor, for example through the super keyword in Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

), and it usually has different rules for scope modifiers. Constructors are often distinguished by having the same name as the declaring class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

. They have the task of initializing the object's data members and of establishing the invariant
Invariant (computer science)
In computer science, a predicate is called an invariant to a sequence of operations provided that: if the predicate is true before starting the sequence, then it is true at the end of the sequence.-Use:...

 of the class, failing if the invariant isn't valid. A properly written constructor will leave the object
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...

 in a valid state. Immutable object
Immutable object
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created...

s must be initialized in a constructor.

Programmers can also use the term constructor to denote one of the tags that wraps data in an algebraic data type
Algebraic data type
In computer programming, particularly functional programming and type theory, an algebraic data type is a datatype each of whose values is data from other datatypes wrapped in one of the constructors of the datatype. Any wrapped datum is an argument to the constructor...

. This is a different usage than in this article. For more information, see algebraic data type
Algebraic data type
In computer programming, particularly functional programming and type theory, an algebraic data type is a datatype each of whose values is data from other datatypes wrapped in one of the constructors of the datatype. Any wrapped datum is an argument to the constructor...

.

Most languages allow overloading
Method overloading
Function overloading or method overloading is a feature found in various programming languages such as Ada, C#, VB.NET, C++, D and Java that allows the creation of several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the...

 the constructor 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:

Parameterized constructors

The constructors that can take arguments are termed as parameterized constructors. For example:

class example
{
int p, q;
public:
example(int a, int b); //parameterized constructor
};
example :: example(int a, int b)
{
p = a;
q = b;
}

When an object is declared in a parameterized constructor, the initial values have to be passed as arguments to the constructor function. The normal way of object declaration may not work. The constructors can be called explicitly or implicitly.The method of calling the constructor implicitly is also called the shorthand method.

example e = example(0, 50); //explicit call

example e(0, 50); //implicit call

Default constructors

Default constructors
Default constructor
In computer programming languages the term “default constructor” refers to a constructor that is automatically generated in the absence of explicit constructors ; this automatically provided constructor is usually a nullary constructor...

 define the actions to be performed by the compiler when a class object is instantiated without actual parameters.

Copy constructors

Copy constructors
Copy constructor
A copy constructor is a special constructor in the C++ programming language creating a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed , which might be followed by parameters of any type...

 define the actions performed by the compiler when copying class objects. A copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object).

It is used to create a copy of an existing object of the same
class. Even though both classes are the same, it counts as a conversion
constructor.

Dynamic constructors

Allocation of memory to objects at the time of their construction is known as dynamic construction of objects and such constructors are called as dynamic constructors. This results in saving of memory as it enables the system to allocate the right amount of memory for each object when the objects are not of the same size. The memory is allocated with the help of the new operator. For example,

class example
{
char *name;
int length;
public:
example // constructor - 1
{
length = 0;
name = new char[length + 1];
}
example(char *e)
{
length strlen(e); // constructor - 2
name = new char[length + 1];
strcpy(name, e);
}
void join(example &a, example &b);
};
void example :: join(example &a, example &b)
{
length = a.length + b.length;
delete name;
name = new char[length + 1]; // dynamic allocation
strcpy(name, a.name);
strcat(name, b.name);
};

Conversion constructors

Conversion constructors provide a means for a compiler to implicitly create an object of a class from an object another type.

Constructors syntax

    • Java
      Java (programming language)
      Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

      , C++
      C++
      C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

      , C#, ActionScript
      ActionScript
      ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

      , and , have a naming convention in which constructors have the same name as the class of which they are associated with.
    • In PHP 5 a recommended name for a constructor is __construct. For backwards compatibility, a method with the same name as the class will be called if __construct method can not be found. Since PHP 5.3.3, this works only for non-namespaced classes.
    • In Perl
      Perl
      Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

       constructors are, by convention, named "new" and have to do a fair amount of object creation.
    • In Moose object system for Perl, constructors (named new) are automatically created and are extended by specifying a BUILD method.
    • In Visual Basic .NET
      Visual Basic .NET
      Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

      , the constructor is called "New".
    • In Python
      Python (programming language)
      Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

      , the constructor is called "__init__" and is always passed its parent class as an argument, the name for which is generally defined as "self".
    • Object Pascal
      Object Pascal
      Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...

       constructors are signified by the keyword "constructor" and can have user-defined names (but are mostly called "Create").
    • In Objective-C
      Objective-C
      Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...

      , the constructor method is split across two methods, "alloc" and "init" with the alloc method setting aside (allocating) memory for an instance of the class, and the init method handling the bulk of initializing the instance. A call to the method "new" invokes both the alloc and the init methods, for the class instance.

Java

In Java
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, some of the differences between other methods and constructors are:
  • 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, or static.
  • Constructors are always executed by the same thread.


Apart from this, a Java constructor performs the following functions in the following order:
  1. 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.)
  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.

In Java, C#, and VB .NET for reference types the constructor creates objects in a special part of memory called
heap. On the other hand the value types (such as int, double etc.), are created in a sequential memory called stack.
VB NET and C# allow use of new to create objects of value types. However, in those languages even use of new for value types creates objects only on stack. In C++ when constructor is invoked without new the objects are created on stack. On the other hand when objects are created using new they are created on heap which must be deleted
implicitly by a destructor or explicitly by a call to operator delete.

Most languages provides a default constructor if programmer provides no constructor. However, this language provided constructor is taken away as soon as programmer provides any constructor in the class code. In C++ a default constructor is REQUIRED if an array of class objects is to be created. Other languages (Java, C#, VB .NET) have no such restriction.

In C++ copy constructor is called implicitly when class objects are returned from a method by return mechanism or when class objects are passed by value to a function. C++ provides a copy constructor if programmer provides no constructor at all. That is taken away as soon as any constructor is provided by the programmer. C++ provided copy constructor ONLY makes member-wise copy or shallow copies. For deep copies a programmer written copy constructor that makes deep copies will be required. Generally a rule of three is observed. For a class that should have a copy constructor to make deep copies, the three below must be provided.
1. Copy constructor
2. Overloading of assignment operator.
3. A destructor.
The above is called rule of three in C++. If cloning of objects is not desired in C++ then copy constructor must be declared private.

Example


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

//overloading a constructor
public Example(int input)
{
data = input; //This is an assignment
}

//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

In Visual Basic .NET
Visual Basic .NET
Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework...

, constructors 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")

Example


public class MyClass
{
private int a;
private string b;

//constructor
public MyClass : this(42, "string")
{
}

//overloading a 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

In C#, a static constructor 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 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
Singleton pattern
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system...

. When used in a generic programming
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...

 class, static constructors are called on every new generic instantiation one per type (static variables are instantiated as well).

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;

C++

In C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

, the name of the constructor is the name of the class. It does not return anything. It can have parameters, like any member functions (methods). Constructor functions should be declared in the public section.

The constructor has two parts. First is the initializer list which comes after the parameter list
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...

 and before the opening curly bracket of the method's body. It starts with a colon and separated by commas. You are not always required to have initializer list, but it gives the opportunity to construct data members with parameters so you can save time (one construction instead of a construction and an assignment). Sometimes you must have initializer list for example if you have const or reference type data members, or members that cannot be default constructed (they don't have parameterless constructor). The order of the list should be the order of the declaration of the data members, because the execution order is that. The second part is the body which is a normal method body surrounded by curly brackets.

C++ allows more than one constructor. The other constructors cannot be called, but can have default values for the parameters. The constructor of a base class (or base classes) can also be called by a derived class. Constructor functions cannot be inherited and their addresses cannot be referred. When memory allocation is required, the operators new and delete are called implicitly.

A copy constructor has a parameter of the same type passed as const reference, for example Vector(const Vector& rhs). If it is not implemented by hand the compiler gives a default implementation which uses the copy constructor for each member variable or simply copies values in case of primitive types. The default implementation is not efficient if the class has dynamically allocated members (or handles to other resources), because it can lead to double calls to delete (or double release of resources) upon destruction.

Example


class Foobar {
public:
Foobar(double r = 1.0, double alpha = 0.0) // Constructor, parameters with default values.
: x(r*cos(alpha)) // <- Initializer list
{
y = r*sin(alpha); // <- Normal assignment
}
// Other member functions
private:
double x; // Data members, they should be private
double y;
};

Example invocations:

Foobar a,
b(3),
c(5, M_PI/4);

You can write a private data member function at the top section before writing public specifier.
If you no longer have access to a constructor then you can use the destructor.

Failure

A constructor that cannot create a valid value should throw an exception
Exception handling
Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution....

. This is because exceptions should be thrown when post-conditions
Postcondition
In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Postconditions are sometimes tested using assertions within the code itself...

 cannot be met, and the post-condition of a constructor is the existence of a valid object. An object which throws during its constructor never comes into existence (although some of its member objects might). This affects how one handles errors and special consideration must be given for exceptions emitted by member variables' constructorshttp://www.gotw.ca/gotw/066.htm.

F#

In F#, a constructor can include 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
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...

, the routines which initialize new objects are called creation procedures. They are similar to constructors in some ways and different in others. Creation procedures have the following traits:
  • Creation procedures never have an explicit return type (by definition of procedure).Eiffel routines are either procedures or functions. Procedures never have a return type. Functions always have a return type.
  • 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 must leave the newly initialized object in a state that satisfies the class invariant.Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.


Although object creation involves 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.The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.
  • 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

ColdFusion
ColdFusion
In computing, ColdFusion is the name of a commercial rapid application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion was originally designed to make it easier to connect simple HTML pages to a database, by version 2 it had...

 has no constructor method. Developers using it commonly create an 'init' method that acts as a pseudo-constructor.

Example













Pascal

In Object Pascal
Object Pascal
Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...

, the constructor is similar to a factory method. The only syntactic difference to regular methods is the keyword constructor in front of the name (instead of procedure or function). It can have any name, though the convention is to have Create as prefix, such as in CreateWithFormatting. Creating an instance of a class works like calling a static method of a class: TPerson.Create("Peter").

Example


program Program;

interface

type
TPerson = class
private
FName: string;
public
property Name: string read FName;
constructor Create(AName: string);
end;

implementation

constructor TPerson.Create(AName: string);
begin
FName := AName;
end;

var
Person: TPerson;
begin
Person := TPerson.Create("Peter"); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = "Peter"
end;

Perl

In Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

 version 5, by default, constructors must provide code to create the object (a reference, usually a hash reference, but sometimes an array reference, scalar reference or code reference) and bless it into the correct class. By convention the constructor is named new, but it is not required, or required to be the only one. For example, a Person class may have a constructor named new as well as a constructor new_from_file which reads a file for Person attributes, and new_from_person which uses another Person object as a template.

Example


package Person;
use strict;
use warnings;
  1. constructor

sub new {
# class name is passed in as 0th
# argument
my $class = shift;
# check if the arguments to the
# constructor are key => value pairs
die "$class needs arguments as key => value pairs"
unless (@_ % 2 0);
# default arguments
my %defaults;

# create object as combination of default
# values and arguments passed
my $obj = {
%defaults,
@_,
};
# check for required arguments
die "Need first_name and last_name for Person"
unless ($obj->{first_name} and $obj->{last_name});
# any custom checks of data
if ($obj->{age} && $obj->{age} < 18)) { # no under-18s
die "No under-18 Persons";
}
# return object blessed into Person class
bless $obj, $class;
}
1;


Perl with Moose
With the Moose object system for Perl, most of this boilerplate can be left out, a default new is created, attributes can be specified, as well as whether they can be set, reset, or are required. In addition, any extra constructor functionality can be included in a BUILD method which the Moose generated constructor will call, after it has checked the arguments. A BUILDARGS method can be specified to handle constructor arguments not in hashref / key => value form.

Example


package Person;
  1. enable Moose-style object construction

use Moose;
  1. first name ( a string) can only be set at construction time ('ro')

has first_name => (is => 'ro', isa => 'Str', required => 1);
  1. last name ( a string) can only be set at construction time ('ro')

has last_name => (is => 'ro', isa => 'Str', required => 1);
  1. age (Integer) can be modified after construction ('rw'), and is not required
  2. to be passed to be constructor. Also creates a 'has_age' method which returns
  3. true if age has been set

has age => (is => 'rw', isa => 'Int', predicate => 'has_age');
  1. Check custom requirements

sub BUILD {
my $self = shift;
if ($self->has_age && $self->age < 18) { # no under 18s
die "No under-18 Persons";
}
}
1;


In both cases the Person class is instiated like this:

use Person;
my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );


PHP
In PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 (version 5 and above), the constructor is a method named __construct, which the keyword new automatically calls 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.

Example


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. In PHP 5 for reasons of backwards compatibility with PHP 4, when method called __construct is not found, a method with the same name as the class will be called instead. Since PHP 5.3.3 this fallback mechanism will only work for non-namespaced classes.


class Person
{
private $name;

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

function getName
{
return $this->name;
}
}

Python
In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, constructors are created by defining an __new__ method, and are called when a new instance is created by calling the class. Unlike other languages such as C++, derived classes in Python do not call their base classes' constructors. However, when a constructor is not defined, the next one found in the class's Method Resolution Order
C3 linearization
In computing, the C3 superclass linearization is an algorithm used primarily to obtain a consistent linearization of a multiple inheritance hierarchy in object-oriented programming. This linearization is used to resolve the order in which methods should be inherited, and is often termed "MRO" for...

 will be called. Due to Python's use of duck typing
Duck typing
In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface...

, class members are often defined in the constructor, rather than in the class definition itself.

In case of the initial values (not methods) are needed, the __init__ method can be defined.

Example


class ExampleClass(object):
def __new__(self):
# We override the constructor to return none instead.
return None

exampleInstance = ExampleClass
print exampleInstance
None

Constructors simplified, with pseudocode
Constructors are always part of the implementation of classes. A class (in programming) refers to a specification of the general traits of the set of objects that are members of the class rather than the specific traits of any object at all. A simple analogy in pseudocode
Pseudocode
In computer science and numerical computation, pseudocode is a compact and informal high-level description of the operating principle of a computer program or other algorithm. It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading...

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 just provides 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, traits, 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 ...
}
// ...
}
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK