aspose file tools
The moose likes Beginning Java and the fly likes Cloning Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Cloning " Watch "Cloning " New topic
Author

Cloning

neil johnson
Greenhorn

Joined: Dec 03, 2008
Posts: 23
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
Sheriff

Joined: Oct 13, 2005
Posts: 32654
    
    4
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

Joined: Oct 27, 2005
Posts: 19216

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().


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cloning
 
Similar Threads
Understanding superclass and subclass objects
Cloning - a doubt regarding super.clone()
Question regarding Cloneable interface and Subclasses
clone()
Can I clone my class like this?