• 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
  • Frits Walraven
  • Carey Brown
  • Tim Holloway


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?

Posts: 64714
  • 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.
Posts: 21760
Eclipse IDE Spring VI Editor Chrome Java Ubuntu 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!