Copy Constructor

Author: Ravi Poswal

Each non-static method & constructor has an implicit parameter named this which holds the reference of the invoking object. A method or constant that receives the reference of a called method uses the "this" parameter.

1. It is used in a constructor or method to find the data member of an object. When the names of an object's data member and the local user of a method conflict

Code Example

class AB{
int a,b;
public AB (int a,int b){
this.a=a;
this.b=b;}
public void display(){
System.out.println("a="+ a);
System.out.println("b="+b);
}
public static void main(String s[]){
AB x= new AB(5,6);
x.display();
}
}

It makes constructor chaining easier. It is the ability to call a class's constructor from another class's or another class's constructor.
Syntax: -
this (Args if any)
Note: -
When this keyword is used for invoking a constructor, it must be the first statement of the constructor.

Code Example

class AB{
int a,b;
public AB(){
this (2,4); // call another constructor
System.out.println("In default");
}
public AB (int x) { this(x,4);
System.out.println("In one paremitrized");
}
public AB(int x,int y){
a=x;
b=y;
System.out.println("In two Paramitrized");
}
public static void main(String s[]){
AB x= new AB();
x.display();
AB y= new AB(10);
y.display();
AB z= new AB(20,40);
z.display();
}
public void display(){
System.out.println("a="+ a);
System.out.println("b="+b);
}}

It helps with method chaining. It is the ability to use several methods on an object in a single sentence. this will be covered using two different conditions.

1. Without method chaining

2. With method chaining

Code Example

//Without method chaining
class AB{     
int a,b;
public AB(int x, int y){
a=x;
b=y;
}
public void display(){
System.out.println("a="+a);
System.out.println("b="+b);
}
public static void main(String s[]){
AB x= new AB(4,5);
x.display();
x.swap();
x.display();
}
public void swap(){ 
int c=a;
a=b;
b=c;
}}

Code Example

class AB
{
int a,b;
public AB(int x,int y){
a=x;
b=y; // implicitly this is being returned
}
public AB Swap(){
int c=a;
a=b;
b=c;
return this;}
public AB display()
{
System.out.println("a="+a);
System.out.println("b="+b);
return this;
}
public static void main(String sr[])
{
AB x= new AB(4,5);
x.display().swap().display();
}
}