• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Cloning

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?


 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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().
reply
    Bookmark Topic Watch Topic
  • New Topic