Recent

7.Copy Constructor in Java

Copy constructor is used to create duplicate copy of an existing object.

 

Example:

class Temp

{

int x;

int y;

 

Temp(int x, int y)

{

this.x = x;

this.y = y;

}

 

void show()

{

System.out.println(x);

System.out.println(y);

}

 

Temp(Temp z)

{

this.x =z.x;

this.y =z.y;

}

 

public static void main(String[] s)

{

System.out.println("initial values");

Temp t1 = new Temp(10,20);

t1.show();

 

System.out.println("\n copied values from object t1");

 

Temp t2 = new Temp(t1);   //reference of Object t1 is passed in

t2.show();                //the constructor to create copy of

}}                        //t1 in t2 (only reference is passed).

Output:

initial values
10
20
copied values from object t1
10
20

POINTS TO REMEMBER

·         whenever we are passing address of variable, it is called call by reference. whenever we are passing values of variable, it is called call by value.

·         In Java call by reference is not supported to enhance the security of Java application.

Question: Is it possible to have a class without constructor?

Answer: NO, no class can exist without a constructor in Java. Consider this example:

class Temp

{

void show()

{

System.out.println("Show Function");

}

public static void main(String[] s)

{

Temp t = new Temp();

t.show();

}}

> In this program we can see that there is no Temp() in the class. But compiler checks the unique existence of constructor, if it found then it is ok else it adds a non-parameterized constructor implicitly.  Therefore we are getting a constructor by default, so it is called default constructors.

 

Question: How to define a Constructor?

Answer: We can define a constructor as >>Classname(){ //Constructor Body}

Here Classname is the name of your class.

Question: Can we overload a constructor?

Answer: Yes, We can overload a constructor just like a method by changing the number and type of arguments.

Question: What will happen if we put a return type before the Constructor?

Answer: Nothing will happen, the compiler will treat them as a function.

For example: 

class Temp

{

 

Temp()

{

System.out.println("Default");

}

 

void Temp()  //this will be treated as a function & not a constructor

{

System.out.println("Hello");

}

 

public static void main(String[] s)

{

new Temp();

}

}

 Output:

Default

Question: When a compiler adds a default constructor implicitly?

Answer: Whenever there is no constructor in the class then compiler adds a non-parameterized constructor inside the class. If there is any constructor(parameterized or non parameterized) present in the program then compiler do not any constructor by default.

No comments:

Post a Comment

Bug-dbug Designed by Bugdbug - Developed by Belson Raja Copyright © 2016

Theme images by Bim. Powered by Blogger.
Published By Bugdbug India