1
Animal animal = new Animal(101);              //Constructor is executed.

Animal clone=(Animal)animal.clone()     //Constructor is not executed. Why ?
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Javed Solkar
  • 162
  • 11

2 Answers2

3

The default implementation of the clone() method given in the Object class does not call any kind of constructor.

It makes a "shallow copy" of object, because it creates copy of Object by creating new instance and then copying content by assignment, which means if your Class contains a mutable field, then both original object and clone will refer to same internal object.

Try to have a look at this page.

riccardo.cardin
  • 7,971
  • 5
  • 57
  • 106
0

Your constructor isn't called because you are calling the clone() method. Based on the way how the clone method is implemented, it does not need to call the constructor.

One way to involve the constructor would be by implementing the clone method with a copy constructor, like so:

public class A implements Cloneable{

private int example;

public A(){
//this is the default constructor, normally not visible and normally not needed, 
//but needed in this case because you supply another constructor
}

public A(A other){
    this.example = other.example;
}

//You may specify a stronger type as return type
public A clone(){
    return new A(this);
}

}

Now, every time you call the clone method, the copy constructor (the one with the A-parameter) is called.

regards me

Christian
  • 609
  • 8
  • 22
  • 1
    Your class must implement `Clonable`, or a `CloneNotSupported` will be thrown. – riccardo.cardin Mar 18 '15 at 14:27
  • Yeah sorry, I forgot it because I did not write it in an IDE;) I added it now and upvoted your comment ;) – Christian Mar 18 '15 at 14:33
  • I think you should modify your answer, because your example is not correct. Take a look at [this answer](http://stackoverflow.com/questions/1052340/what-is-wrong-with-this-clone/1053227#1053227). – riccardo.cardin Mar 18 '15 at 15:58
  • 1
    Do not call the constructor, rather call `super.clone()`. See http://stackoverflow.com/questions/1052340/what-is-wrong-with-this-clone/1053227#1053227 – Steve Kuo Mar 18 '15 at 16:05