Well ..good explanation.
Now ...have some interesting issues ;)
-
public class MyClass implements Cloneable/*The previous error i fixed it here ;)*/ {
-
public MyClass(...){} //plain constructor
-
public MyClass(MyClass obj){ //copy constructor
-
this(...);
-
}
-
public Object clone() throws CloneNotSupportedException{
-
return super.clone(); //this implementation is required because clone is protected in Object class
-
}
-
//some code goes here
-
}
-
Now my creation of objects goes here.
-
MyClass obj = new MyClass(...);
-
Here what happens, if the class is in first time use then class gets loaded(the class loading ... needs lot of work) then allocates the memory for the new object and then calls the plain constructor.
-
MylCass clone_obj = (MyClass)obj.clone();
-
Here, the source object(here obj) required(class loading removed here). First it allocates the memory and then simply copies the states of object.Cloning an object, it does not call the constructor. Is it right?
Again i am creating an object using plain construtor.
-
MyClass second_obj = new MyClass(...);
-
Here class loading removed. It allocates memory and then calls the plain constructor. Cloning of an object and creating an object using plain constructor, the difference is no source object required and one more thing what i think that in case of cloning
Native call required. Is it a more headache than simply calling the constructor?
-
MyClass source_obj = new MyClass(...);
-
MyClass copy_obj = new MyClass(source_obj);
-
Here it also needs a source object.Memory allocation and calling a constructor(copy), it's mostly same as cloning an object as well as creating a new object(using plain constructor) after the class gets loaded.
But you told that it's better to use copy constructor than cloning an object.
The reason is because of
native call or something else?
If any wrong with my explanation then pleas correct it ;)