Copy Constructor Call Assignment Operator Java

In class-basedobject-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

A constructor resembles an instance method, but it differs from a method in that it has no explicit return type, it is not implicitly inherited and it usually has different rules for scope modifiers. Constructors often have the same name as the declaring class. They have the task of initializing the object's data members and of establishing the invariant of the class, failing if the invariant is invalid. A properly written constructor leaves the resulting object in a valid state. Immutable objects must be initialized in a constructor.

Most languages allow overloading the constructor in that there can be more than one constructor for a class, with differing parameters. Some languages take consideration of some special types of constructors. Constructors, which concretely use a single class to create objects and return a new instance of the class, are abstracted by factories, which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an object pool.


Defined constructors[edit]

Constructors that can take at least one argument are termed as parameterized constructors. For example:

classExample{intx,y;public:Example();Example(inta,intb);// Parameterized constructor};Example::Example(){}Example::Example(inta,intb){x=a;y=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.

Examplee=Example(0,50);// Explicit callExamplee(0,50);// Implicit call

Default constructors[edit]

If the programmer does not supply a constructor for an instantiable class, most languages will provide a default constructor.

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.

Some languages (Java, C#, VB .NET) will default construct arrays of class types to contain null references. Languages without null references may not allow default construction of arrays of non default constructible objects, or require explicit initialization at the time of the creation (C++):

#include<iostream>classstudent{public:inta,b;student(a=0,b=0)//default constructor};intmain(){}

Copy constructors[edit]

See also: Copy constructor (C++)

Copy constructors 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.

While copy constructors are usually abbreviated copy ctor or cctor, they have nothing to do with class constructors used in .NET using the same abbreviation.

Conversion constructors[edit]

Conversion constructors provide a means for a compiler to implicitly create an object belonging to one class based on an object of a different type. These constructors are usually invoked implicitly to convert arguments or operands to an appropriate type, but they may also be called explicitly.

Move constructors[edit]

In C++, move constructors take a value reference to an object of the class, and are used to implement ownership transfer of the parameter object's resources.


  • Java, C++, C#, ActionScript, and PHP 4 have a naming convention in which constructors have the same name as the class with which they are associated.
  • In PHP 5, a recommended name for a constructor is . For backwards compatibility, a method with the same name as the class will be called if method can not be found. Since PHP 5.3.3, this works only for non-namespaced classes.[1]
  • In Perl, 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, the constructor is called "".
  • In Python, the constructor is split over two methods, "" and "". The method is responsible for allocating memory for the instance, and receives the class as an argument (conventionally called ""). The method (often called "the initialiser") is passed the newly created instance as an argument (conventionally called "").[2]
  • Object Pascal constructors are signified by the keyword "" and can have user-defined names (but are mostly called "").
  • In Objective-C, the constructor method is split across two methods, "" and "" with the method setting aside (allocating) memory for an instance of the class, and the method handling the bulk of initializing the instance. A call to the method "" invokes both the and the methods, for the class instance.

Memory organization[edit]

In Java, C# and VB .NET the constructor creates objects in a special memory structure called heap for reference types. Value types (such as int, double etc.), are created in a sequential structure 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. When objects are created using new they are created on heap. They must be deleted implicitly by a destructor or explicitly by a call to operator delete.

Language details[edit]


In Java, constructors differ from other methods in that:

  • Constructors never have an explicit return type.
  • Constructors cannot be directly invoked (the keyword “” invokes them).
  • Constructors cannot be synchronized, final, abstract, native, or static.

Java constructors perform the following tasks in the following order:

  1. Call the default constructor of the superclass if no constructor is defined.
  2. Initialize member variables to the specified values.
  3. Executes the body of the constructor.

Java permit users to call one constructor in another constructor using keyword. But must be first statement. [3]

classExample{Example()//non-parameterized constructor{this(1);//calling of constructorSystem.out.println("0-arg-cons");}Example(inta)//parameterized constructor{System.out.println("1-arg-cons");}publicstaticvoidmain(String[]args){Examplee=newExample();}

Java provides access to the superclass's constructor through the keyword.

publicclassExample{// Definition of the constructor.publicExample(){this(1);}// Overloading a constructorpublicExample(intinput){data=input;// This is an assignment}// Declaration of instance variable(s).privateintdata;}
// Code somewhere else// Instantiating an object with the above constructorExamplee=newExample(42);

A constructor taking zero number of arguments is called a "no-arguments" or "no-arg" constructor.[4]


As of ES6, JavaScript has direct constructors like many other programming languages. They are written as such


This can be instantiated as such


The equivalent of this before ES6, was creating a function that instantiates an object as such


This is instantiated the same way as above.

Visual Basic .NET[edit]

In Visual Basic .NET, constructors use a method declaration with the name "".

ClassFoobarPrivatestrDataAsString' ConstructorPublicSubNew(ByValsomeParamAsString)strData=someParamEndSubEndClass
' code somewhere else' instantiating an object with the above constructorDimfooAsNewFoobar(".NET")


Example C# constructor:

publicclassMyClass{privateinta;privatestringb;// ConstructorpublicMyClass():this(42,"string"){}// Overloading a constructorpublicMyClass(inta,stringb){this.a=a;this.b=b;}}
// Code somewhere// Instantiating an object with the constructor aboveMyClassc=newMyClass(42,"string");

C# static constructor[edit]

In C#, a static constructor is a static data initializer. Static constructors are also called class constructors. Since the actual method generated has the name .cctor they are often also called "cctors".[5][6]

Static constructors allow complex static variable initialization.[7] Static constructors are called implicitly when the class is first accessed. Any call to a class (static or constructor call), triggers the static constructor execution. 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.

publicclassMyClass{privatestaticint_A;// Normal constructorstaticMyClass(){_A=32;}// Standard default constructorpublicMyClass(){}}
// Code somewhere// Instantiating an object with the constructor above// right before the instantiation// The variable static constructor is executed and _A is 32MyClassc=newMyClass();


In C++, the name of the constructor is the name of the class. It returns nothing. It can have parameters like any member function. Constructor functions are usually declared in the public section, but can also be declared in the protected and private sections, if the user wants to restrict access to them.

The constructor has two parts. First is the initializer list which follows the parameter list and before the method body. It starts with a colon and entries are comma-separated. The initializer list is not required, but offers the opportunity to provide values for data members and avoid separate assignment statements. The initializer list is required if you have const or reference type data members, or members that do not have parameterless constructor logic. Assignments occur according to the order in which data members are declared (even if the order in the initializer list is different).[8] The second part is the body, which is a normal method body enclosed in curly brackets.

C++ allows more than one constructor. The other constructors must have different parameters. Additionally constructors which contain parameters which are given default values, must adhere to the restriction that not all parameters are given a default value. This is a situation which only matters if there is a default constructor. The constructor of a base class (or base classes) can also be called by a derived class. Constructor functions are not inherited and their addresses cannot be referenced. When memory allocation is required, the new and delete operators 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 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.

classFoobar{public:Foobar(doubler=1.0,doublealpha=0.0)// Constructor, parameters with default values.:x(r*cos(alpha))// <- Initializer list{y=r*sin(alpha);// <- Normal assignment}private:doublex;doubley;};

Example invocations:


On returning objects from functions or passing objects by value, the objects copy constructor will be called implicitly, unless return value optimization applies.

C++ implicitly generates a default copy constructor which will call the copy constructors for all base classes and all member variables unless the programmer provides one, explicitly deletes the copy constructor (to prevent cloning) or one of the base classes or member variables copy constructor is deleted or not accessible (private). Most cases calling for a customized copy constructor (e.g. reference counting, deep copy of pointers) also require customizing the destructor and the copy assignment operator. This is commonly referred to as the Rule of three.


In F#, a constructor can include any or statements defined in a class. statements define private fields and statements execute code. Additional constructors can be defined using the keyword.

typeMyClass(_a:int,_b:string)=class// Primary constructorleta=_aletb=_bdoprintfn"a = %i, b = %s"ab// Additional constructorsnew(_a:int)=MyClass(_a,"")thenprintfn"Integer parameter given"new(_b:string)=MyClass(0,_b)thenprintfn"String parameter given"new()=MyClass(0,"")thenprintfn"No parameter given"end
// Code somewhere// instantiating an object with the primary constructorletc1=newMyClass(42,"string")// instantiating an object with additional constructorsletc2=newMyClass(42)letc3=newMyClass("string")letc4=MyClass()// "new" keyword is optional


In Eiffel, the routines which initialize new objects are called creation procedures. Creation procedures have the following traits:

  • Creation procedures have no explicit return type (by definition of procedure).[a]
  • Creation procedures are named.
  • Creation procedures are designated by name as creation procedures in the text of the class.
  • Creation procedures can be explicitly 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.[b]

Although object creation involves some subtleties,[9] the creation of an attribute with a typical declaration as expressed in a creation instruction consists of the following sequence of steps:

  • Create a new direct instance of type .[c]
  • Execute the creation procedure to the newly created instance.
  • Attach the newly initialized object to the entity .

In the first snippet below, class is defined. The procedure is coded after the keyword .

The keyword introduces a list of procedures which can be used to initialize instances. In this case the list includes , a procedure with an empty implementation inherited from class , and the procedure coded within the class.

classPOINTcreatedefault_create,makefeaturemake(a_x_value:REAL;a_y_value:REAL)dox:=a_x_valuey:=a_y_valueendx:REAL-- X coordinatey:REAL-- Y coordinate...

In the second snippet, a class which is a client to has a declarations and of type .

In procedural code, is created as the origin (0.0, 0.0). Because no creation procedure is specified, the procedure inherited from class is used. This line could have been coded . Only procedures named as creation procedures can be used in an instruction with the keyword. Next is a creation instruction for , providing initial values for the 's coordinates. The third instruction makes an ordinary instance call to the procedure to reinitialize the instance attached to with different values.



CFML uses a method named '' as a constructor method.


component{// propertiespropertyname="cheeseName";// constructorfunctionCheeseinit(requiredstringcheeseName){variables.cheeseName=arguments.cheeseName;returnthis;}}

Create instance of a cheese.


Since ColdFusion 10,[10] CFML has also supported specifying the name of the constructor method:

componentinitmethod="Cheese"{// propertiespropertyname="cheeseName";// constructorfunctionCheeseCheese(requiredstringcheeseName){variables.cheeseName=arguments.cheeseName;returnthis;}}

Object Pascal[edit]

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

programOopProgram;typeTPerson=classprivateFName:string;publicpropertyName:stringreadFName;constructorCreate(AName:string);end;constructorTPerson.Create(AName:string);beginFName:=AName;end;varPerson:TPerson;beginPerson:=TPerson.Create('Peter');// allocates an instance of TPerson and then calls TPerson.Create with the parameter AName = 'Peter'end.


In Perl programming language version 5, by default, constructors are factory methods, 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.

packagePerson;# In Perl constructors are named 'new' by convention.subnew{# Class name is implicitly passed in as 0th$class=shift;# Default attribute values, if you have>"bar");# Initialize attributes as a combination of default values and arguments$self={%defaults,@_};# Check for required arguments, class invariant, etc.if(notdefined$self->{first_name}){die"Mandatory attribute missing in Person->new(): first_name";}if(notdefined$self->{last_name}){die"Mandatory attribute missing in Person->new(): last_name";}if(defined$self->{age}and$self->{age}<18){die"Invalid attribute value in Person->new(): age < 18";}# Perl makes an object belong to a class by 'bless'.bless$self,$class;return$self;}1;

Perl with Moose[edit]

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.

packagePerson;# enable Moose-style object constructionuseMoose;# first name ( a string) can only be set at construction time ('ro')hasfirst_name=>(is=>'ro',isa=>'Str',required=>1);# last name ( a string) can only be set at construction time ('ro')haslast_name=>(is=>'ro',isa=>'Str',required=>1);# age (Integer) can be modified after construction ('rw'), and is not required# to be passed to be constructor. Also creates a 'has_age' method which returns# true if age has been sethasage=>(is=>'rw',isa=>'Int',predicate=>'has_age');# Check custom requirementssubBUILD{my$self=shift;if($self->has_age&&$self->age<18){# no under 18sdie"No under-18 Persons";}}1;

In both cases the Person class is instiated like this:



In PHP version 5 and above, the constructor is a method named (notice that it's a double underscore), which the keyword 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 statement is written, you also need to send the constructor arguments for the parameters.[1]



In Python, constructors are defined by one or both of and methods. A new instance is created by calling the class as if it were a function, which calls the and methods. If a constructor method is not defined in the class, the next one found in the class's Method Resolution Order will be called.[11]

In the typical case, only the method need be defined. (The most common exception is for immutable objects.)

>>> classExampleClass(object):... def__new__(cls,value):... print("Creating new instance...")... # Call the superclass constructor to create the instance.... instance=super(ExampleClass,cls).__new__(cls)... returninstance... def__init__(self,value):... print("Initialising instance...")... self.payload=value>>> exampleInstance=ExampleClass(42)Creating new instance...Initialising instance...>>> print(exampleInstance.payload)42

Classes normally act as 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 method is permitted to return something other than an instance of the class for specialised purposes. In that case, the is not invoked.[12]


In Ruby, constructors are created by defining a method called . This method is executed to initialize each new instance.

irb(main):001:0> classExampleClassirb(main):002:1> definitializeirb(main):003:2> puts"Hello there"irb(main):004:2> endirb(main):005:1> end=> nilirb(main):006:0> ExampleClass.newHello there=> #<ExampleClass:0x007fb3f4299118>

See also[edit]



  1. ^Eiffel routines are either procedures or functions. Procedures never have a return type. Functions always have a return type.
  2. ^Because the inherited class invariant must be satisfied, there is no mandatory call to the parents' constructors.
  3. ^The Eiffel standard requires fields to be initialized on first access, so it is not necessary to perform default field initialization during object creation.

First some basics about copy construction and copy assignment in C++ and Java

C++ and Java are two very different beasts due to object semantics in C++ and Reference semantics in Java. What I mean by this is:

In C++ this line denotes a new object that gets initialized with . In Java, this line creates not a new object but a new reference to an object, and that reference refers to what ever the expression gives. Java references can be null, meaning "no object". C++ objects are, so there is no "no object"-object ;-) Java references are very much like C++ pointers. The only thing that can make the distinction difficult is that while C++ has pointers and objects and dereferences pointers with , in Java everything is a reference (except int and a few other basic types), and accessing objects through references uses , wich easily can be confused with access to "direct" objects in C++. "Everything is a reference" means, that any object (except int & Co.) is conceptually created on the heap.

Having said that, let's have a look at assignments and copies in both languages.

Copy construction means the same in both languages, you essentially create a new object that is a copy of another. Copy constructor definition is similar:

The difference is only that C++ explicitly has to declare the parameter as a reference, while in Java everything is a reference anyways. Writing the first line in C++ would define a constructor that takes it's argument by copy, i.e. the compiler would have to create a copy already, using the copy constructor, for which it has to create a copy,... - not a good idea.

Using copy construction in the two languages will look like this:

When you look at the first and third line, they look essentially the same. This is because they are essentially the same, since Java references are essentially like pointers in C++. Both expressions create a new object that can outlive the function scope it is created in. The second line creates a plain C++ object on the stack, wich does not exist in Java. In C++, copies are also created implicitly by the compiler eg. when an object is passed to a function that accepts its parameter by value instead of by reference.

Defining copy assignment: In C++, you can define wich (normally) assigns the values of an object to an already existing object, discarding the old values of the object you assign to. If you don't define it yourself, the compiler will do it's best to generate one for you, doing a plain elementwise copy of the objects' elements. In Java, you cannot overload operators, so you will have to define a method, called e.g. :

Note thet here again we explicitly declare the parameter as reference in C++ but not in Java.

Using copy assignment:

Here the first two lines look exactly the same but could not be more different. Remember that in C++, and deonte the objects themselves, while in Java they are only references. So in C++ this is copy assignment on objects, meaning you finish with two objects that have the same content. After changing you will have with the value that had before the assignment, while has changed.
In Java (line 2) that assignment is an assignment of references, meaning after that the two references and refer to the very same object, while the object previously referred ba is not referred to any more and so it will be garbage collected. Calling will change the single object both references point to and accessing it through the reference will reveal these changes.
Again it's (nearly) the same with C++ pointers. You see you cannot distinguish the syntax of object and pointer assignment, it's all determined by the types that get assigned. The difference with C++ is that it has no garbace collector and you end up with a memory leak because the object pointed to can not be deleted any more.

About your question:

Consider a C++ class:

Suppose each X object allocates it's own dynamic array of ints, the pointer to it gets stored in . Since C++ has no garbage collection, the X objects have to care themselves for their allocated memory, i.e. they have to destroy it manually:

A copy constructor will copy the dynamic array of the original, so the two do not conflict while using the same array. This is called deep copy and is used equally in Java and C++:

Now to the qoute in your question: Consider two objects x1 and x2 and the assignment . If you leave everythign to the compiler, it will generate an assignment operator like this:

In the first line gets the pointer value of . Like I explained in the section about copy assignment, this will lead to both pointers pointing to the same array, and the array previously owned by will be lost in space, meaning you have a leak and odd behavior when both objects work on their shared array.
The correct implementation would be:

Here you see what the quote says: First, the object is "cleaed up", i.e. the memory is freed, essentially doing what the destructor does ("instance has to be destroyed"). Then, the deep copy is performed, doing what the copy constructor does ("...and re-initialized").

This is called the "Rule of Three": If you have to write your own copy constructor (because the generated one does not what you want it to do), you will mostly have to write your own destructor and assignment operator as well. Since C++11 it has become the "Rule of Five", because you have move assignment and move construction that have to be considered as well.

0 Replies to “Copy Constructor Call Assignment Operator Java”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *