• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cloning  RSS feed

 
neil johnson
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class CoffeeCup implements Cloneable {

public Object clone() {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
// This should never happen
throw new InternalError(e.toString());
}
}
}

in another class i used:
CoffeeCup original = new CoffeeCup();
original.add(75); // Original now contains 75 ml of coffee
CoffeeCup copy = (CoffeeCup) original.clone();

Now i got exact copy of CoffeeCup.

my question is: how the application is creating an subclass object(CoffeeCup) when I call super.clone().
As per my understanding if we call super.clone() that means we are calling Object.clone() -- if that is the case how it is creating the object of sub class?
Is there any underlying implementation that Object class uses for creating the subclass object?


 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please remember the code button when posting.

Cloning is done by the JVM, outside yuoour code, so there are independent mechanisms which you don't find out about.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All you need to know is that Object.clone() will simply create a new object of the exact same type (so in your case CoffeeCup) and copies all fields by using simple assignments. For example:
Line 11 could be replaced with the following:
There are three big differences though:
1) when you use Object.clone(), a sub class can call super.clone() and it will not return an instance of Test but an instance of that sub class.
2) Object.clone() does not call a constructor so no constructor code is executed
3) Object.clone() can also copy final fields

So in short, always use super.clone().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!