Content deleted Content added
m code(the->code (the - Fix a typo in one click Tags: Mobile edit Mobile web edit Advanced mobile edit |
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags |
||
Line 13:
Constructors that can take at least one argument are termed as parameterized constructors. 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. If we want to initialize fields of the class with your own values, then use a parameterized constructor.
<
class Example {
public:
Line 27:
Example::Example(int x, int y) : x_(x), y_(y) {}
</syntaxhighlight>
<
Example e = Example(0, 50); // Explicit call.
Example e2(0, 50); // Implicit call.
</syntaxhighlight>
=== Default constructors ===
If the programmer does not supply a constructor for an instantiable class, Java compiler inserts a default constructor into your code on your behalf. This constructor is known as default constructor. You would not find it in your source code (the java file) as it would be inserted into the code during compilation and exists in .class file. The behavior of the default constructor is language dependent. It may initialize data members to zero or other same values, or it may do nothing at all. In Java, a "default constructor" refer to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class or in the absence of any programmer-defined constructors (e.g. in Java, the default constructor implicitly calls the superclass's nullary constructor, then executes an empty body). All fields are left at their initial value of 0 (integer types), 0.0 (floating-point types), false (boolean type), or null (reference types).
<
#include <iostream>
Line 47:
int b;
};
</syntaxhighlight>
=== Copy constructors ===
Line 104:
But <code>this()</code> must be first statement. <ref>[https://ranjeetkumarmaurya.wordpress.com/2017/02/06/constructor-in-java/ Details on Constructor in java]</ref>
<
class Example
{
Line 121:
Example e = new Example();
}
</syntaxhighlight>
Java provides access to the [[superclass (computer science)|superclass's]] constructor through the <code>super</code> keyword.
<
public class Example
{
Line 143:
private int data;
}
</syntaxhighlight>
<
// Code somewhere else
// Instantiating an object with the above constructor
Example e = new Example(42);
</syntaxhighlight>
A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.<ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html|title= Providing Constructors for Your Classes |author=|publisher=Oracle Corporation|date=2013|accessdate=2013-12-20}}</ref>
Line 157:
As of ES6, [[JavaScript]] has direct constructors like many other programming languages. They are written as such
<
class FooBar {
constructor(baz) {
Line 163:
}
}
</syntaxhighlight>
This can be instantiated as such
<
const foo = new FooBar('7')
</syntaxhighlight>
The equivalent of this before ES6, was creating a function that instantiates an object as such
<
function FooBar (baz) {
this.baz = baz;
}
</syntaxhighlight>
This is instantiated the same way as above.
Line 185:
In [[Visual Basic .NET]], constructors use a method declaration with the name "<code>New</code>".
<
Class Foobar
Private strData As String
Line 194:
End Sub
End Class
</syntaxhighlight>
<
' code somewhere else
' instantiating an object with the above constructor
Dim foo As New Foobar(".NET")
</syntaxhighlight>
=== C# ===
Line 206:
Example [[C Sharp (programming language)|C#]] constructor:
<
public class MyClass
{
Line 224:
}
}
</syntaxhighlight>
<
// Code somewhere
// Instantiating an object with the constructor above
MyClass c = new MyClass(42, "string");
</syntaxhighlight>
==== C# static constructor ====
Line 240:
Static constructors are [[thread safe]] and implement a [[singleton pattern]]. When used in a [[generic programming]] class, static constructors are called at every new generic instantiation one per type. Static variables are instantiated as well.
<
public class MyClass
{
Line 257:
}
}
</syntaxhighlight>
<
// Code somewhere
// Instantiating an object with the constructor above
Line 265:
// The variable static constructor is executed and _A is 32
MyClass c = new MyClass();
</syntaxhighlight>
=== C++ ===
Line 277:
A copy constructor has a parameter of the same type passed as ''const'' reference, for example ''Vector(const Vector& rhs)''. If it is not provided explicitly, the compiler 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.
<
class Foobar {
public:
Line 291:
double y_;
};
</syntaxhighlight>
Example invocations:
<
Foobar a,
b(3),
c(5, M_PI/4);
</syntaxhighlight>
On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless [[return value optimization]] applies.
Line 307:
In [[F Sharp (programming language)|F#]], a constructor can include any <code>let</code> or <code>do</code> statements defined in a class. <code>let</code> statements define private fields and <code>do</code> statements execute code. Additional constructors can be defined using the <code>new</code> keyword.
<
type MyClass(_a : int, _b : string) = class
// Primary constructor
Line 324:
printfn "No parameter given"
end
</syntaxhighlight>
<
// Code somewhere
// instantiating an object with the primary constructor
Line 335:
let c3 = new MyClass("string")
let c4 = MyClass() // "new" keyword is optional
</syntaxhighlight>
=== Eiffel ===
Line 358:
The keyword <code lang="eiffel">create</code> introduces a list of procedures which can be used to initialize instances. In this case the list includes <code lang="eiffel">default_create</code>, a procedure with an empty implementation inherited from class <code lang="eiffel">ANY</code>, and the <code lang="eiffel">make</code> procedure coded within the class.
<
class
POINT
Line 378:
-- Y coordinate
...
</syntaxhighlight>
In the second snippet, a class which is a client to <code lang="eiffel">POINT</code> has a declarations <code lang="eiffel">my_point_1</code> and <code lang="eiffel">my_point_2</code> of type <code lang="eiffel">POINT</code>.
Line 387:
The third instruction makes an ordinary instance call to the <code lang="eiffel">make</code> procedure to reinitialize the instance attached to <code lang="eiffel">my_point_2</code> with different values.
<
my_point_1: POINT
my_point_2: POINT
Line 396:
my_point_2.make (5.0, 8.0)
...
</syntaxhighlight>
=== CFML ===
Line 403:
'''Cheese.cfc'''
<
component {
// properties
Line 414:
}
}
</syntaxhighlight>
Create instance of a cheese.
<
myCheese = new Cheese( 'Cheddar' );
</syntaxhighlight>
Since ColdFusion 10,<ref>[https://wikidocs.adobe.com/wiki/display/coldfusionen/cfcomponent CFComponent]</ref> CFML has also supported specifying the name of the constructor method:
<
component initmethod="Cheese" {
// properties
Line 434:
}
}
</syntaxhighlight>
=== Object Pascal ===
Line 440:
In [[Object Pascal]], the constructor is similar to a [[factory method]]. The only syntactic difference to regular methods is the keyword <code>constructor</code> in front of the name (instead of <code>procedure</code> or <code>function</code>). It can have any name, though the convention is to have <code>Create</code> as prefix, such as in <code>CreateWithFormatting</code>. Creating an instance of a class works like calling a static method of a class: <code>TPerson.Create('Peter')</code>.
<
program OopProgram;
Line 462:
Person := TPerson.Create('Peter'); // allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = 'Peter'
end.
</syntaxhighlight>
=== Perl 5 ===
Line 468:
In [[Perl|Perl programming language]] version 5, by default, constructors are [[factory method]]s, that is, methods that create and return the object, concretely meaning create and return a blessed reference. A typical object is a reference to a hash, though rarely references to other types are used too. By convention the only constructor is named ''new'', though it is allowed to name it otherwise, or to have multiple constructors. 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.
<
package Person;
# In Perl constructors are named 'new' by convention.
Line 497:
}
1;
</syntaxhighlight>
=== Perl 5 with Moose ===
Line 503:
With the [[Moose perl|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.
<
package Person;
# enable Moose-style object construction
Line 525:
}
1;
</syntaxhighlight>
In both cases the Person class is instiated like this:
<
use Person;
my $p = Person->new( first_name => 'Sam', last_name => 'Ashe', age => 42 );
</syntaxhighlight>
=== Perl 6 ===
Line 537:
With Perl 6, even more boilerplate can be left out, given that a default ''new'' method is inherited, 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 will get called to allow for custom initialization. A ''TWEAK'' method can be specified to post-process any attributes already (implicitly) initialized.
<
class Person {
has Str $.first-name is required; # First name (a string) can only be set at
Line 563:
}
}
</syntaxhighlight>
The Person class is instantiated like this:
<
my $p0 = Person.new( first-name => 'Sam', last-name => 'Ashe', age => 42 );
my $p1 = Person.new( first-name => 'grace', last-name => 'hopper' );
say $p1.full-name(); # OUTPUT: «Grace Hopper»
</syntaxhighlight>
Alternatively, the named parameters can be specified using the colon-pair syntax in Perl 6:
<
my $p0 = Person.new( :first-name<Sam>, :last-name<Ashe>, :age(42) );
my $p1 = Person.new( :first-name<Grace>, :last-name<Hopper> );
</syntaxhighlight>
And should you have set up variables with names identical to the named parameters, you can use a shortcut that will use the '''name''' of the variable for the named parameter:
<
my $first-name = "Sam";
my $last-name = "Ashe";
my $age = 42;
my $p0 = Person.new( :$first-name, :$last-name, :$age );
</syntaxhighlight>
=== PHP ===
Line 590:
In [[PHP]] version 5 and above, the constructor is a method named <code>__construct()</code> (notice that it's a double underscore), which the keyword <code>new</code> automatically calls after creating the object. It is usually used to automatically perform initializations such as property initializations. Constructors can also accept arguments, in which case, when the <code>new</code> statement is written, you also need to send the constructor arguments for the parameters.<ref name="php5cpnstructor"/>
<
class Person
{
Line 605:
}
}
</syntaxhighlight>
=== Python ===
Line 613:
In the typical case, only the <code>__init__</code> method need be defined. (The most common exception is for immutable objects.)
<
>>> class ExampleClass(object):
... def __new__(cls, value):
Line 628:
>>> print(exampleInstance.payload)
42
</syntaxhighlight>
Classes normally act as [[Factory (object-oriented programming)|factories]] for new instances of themselves, that is, a class is a callable object (like a function), with the call being the constructor, and calling the class returns an instance of that class. However the <code>__new__</code> method is permitted to return something other than an instance of the class for specialised purposes. In that case, the <code>__init__</code> is not invoked.<ref>[https://docs.python.org/3/reference/datamodel.html#object.__new__ Data model]</ref>
Line 635:
In [[Ruby (programming language)|Ruby]], constructors are created by defining a method called <code>initialize</code>. This method is executed to initialize each new instance.
<
irb(main):001:0> class ExampleClass
irb(main):002:1> def initialize
Line 645:
Hello there
=> #<ExampleClass:0x007fb3f4299118>
</syntaxhighlight>
=== OCaml ===
Line 652:
<ref>[http://caml.inria.fr/pub/docs/manual-ocaml/index.html OCaml manual]</ref>
<
class person first_name last_name =
object
Line 666:
print_endline alonzo#get_last_name (*Church*)
</syntaxhighlight>
== See also ==
|