aspose file tools
The moose likes Java in General and the fly likes Using objects clone() method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Using objects clone() method" Watch "Using objects clone() method" New topic
Author

Using objects clone() method

Jim Janssens
Ranch Hand

Joined: Sep 24, 2004
Posts: 210
I hava a data object which I want to be able to clone. The clone method will instantiate a new data object without copying the data of the original.

Like this;

package a;
public interface Data
{
//methods
}

package a;
public abstract class AbstractData implements Data
{

public Object clone()
{
//reflection thing
return newData;
}
}

public class myData extends AbstractData
{
//Methods
}

Ok, the problem is, that:

public Data getEmptyObject(Data data)
{
Data newObject = data.clone();
}

This doesn't work, I get a 'The method clone() from the type Object is not visible' . First, I don't understand why this is happening. They are all in the same package, so even if clone() is not defined public in the interface, I must be able to call the protected method.

What is the solution to work this out ?

A) placing 'Object clone()' in the interface ? (I feel bad about this, dont know why)

B) do not use the clone method and use an self made method (like cloneData or something) which I put in the interface.

C) ... ?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

You have to do two things to the class you want to be able to clone:

One, override clone() to make it public, and just call "return super.clone()" in your implementation.

Two, declare that the class implements the Cloneable interface.

Why is this necessary, you ask? Because that's how it was designed. It is a good design? Depends on who you ask. It's too complicated, most people agree.


[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Note that the default implementation of clone() only does a shallow copy. In otherwords, if your class has member reference fields, the referenced objects are not cloned. The copy will contain references to the same objects. In order to perform a so-called deep copy, you need to make sure each of the member objects are cloned as well.

Layne


Java API Documentation
The Java Tutorial
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Using objects clone() method
 
Similar Threads
Locking
clone()
clone method?
Shallow Copy implementation Question
clone() mehtod