| Author |
clone problems
|
omar bili
Ranch Hand
Joined: Aug 13, 2004
Posts: 177
|
|
Hi i'm using the clone method, it's giving me an error while i copile it's saying that clone have a private access! how can i fix that is there another way to clone an abject, (it's like a hashMap) thanks
|
 |
Paul Sturrock
Bartender
Joined: Apr 14, 2004
Posts: 10336
|
|
it's saying that clone have a private access!
Well, just don't implement your clone method with the private access modifier.
|
JavaRanch FAQ HowToAskQuestionsOnJavaRanch
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24051
|
|
To make a class publically cloneable, you have to do two things: 1) Declare that the class implements java.lang.Cloneable 2) Override clone() something like this: That's what you need to do, and that's how it's supposed to work. Is this a good design? No. But that's how it works.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Wagner Danda Da Silva Filho
Ranch Hand
Joined: Mar 21, 2003
Posts: 80
|
|
The clone method cames from the java.lang.Object class (where all objects extends). Here is the signature of the method: protected Object clone() throws CloneNotSupportedException When you override this method you are not allowed to restrict its visibility (e.g. "private"), but the contrary is permitted: you can make it "public". Wagner Danda
|
SCJP, SCWCD
|
 |
omar bili
Ranch Hand
Joined: Aug 13, 2004
Posts: 177
|
|
ok, got it thanks, but the thing is that my main class does not implement the clone method, so i cant use the super.clone();
2) Override clone() something like this: code: -------------------------------------------------------------------------------- public Object clone() throws CloneNotSupportedException { return super.clone();} --------------------------------------------------------------------------------
maybe ill have to create my own clone method from nothing, and copy all the variables thanks for the help Omar
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
Originally posted by omar bili: ok, got it thanks, but the thing is that my main class does not implement the clone method, so i cant use the super.clone(); maybe ill have to create my own clone method from nothing, and copy all the variables thanks for the help Omar
In order to support clone(), you ALWAYS have to create your own clone method. However, you only need to copy the variables manually if you need to perform a "deep clone". If you just need a shallow clone, then you should call super.clone() as shown. Note that this typically calls the default clone() method from Object. Layne
|
Java API Documentation
The Java Tutorial
|
 |
 |
|
|
subject: clone problems
|
|
|