It's not a secret anymore!
The moose likes Beginning Java and the fly likes clone method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "clone method?" Watch "clone method?" New topic

clone method?

Jon Lee
Ranch Hand

Joined: Mar 04, 2005
Posts: 134
The clone method is defined as a protected method in java.lang.Object class and every class in Java extends Object. Since subclass can inherite the protected method of its superclass, every class is suppoed to inherite clone method from Object class.

But when I want to invoke clone method of a object, the compiler reports the following error:

Why cant I invoke clone method??

[ March 05, 2005: Message edited by: Jon Lee ]

SCJP 5.0 - 98% (2007)<br />SCWCD 1.4 - 97% (2007)
Jimmy Die
Ranch Hand

Joined: Nov 20, 2003
Posts: 97

Do you have a class CloneTest. Just put the rest of your code in the thread. Holding back on the code makes it harder to answer.

Jimmy Die
Jon Lee
Ranch Hand

Joined: Mar 04, 2005
Posts: 134

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The rules governing this are subtle, and have been discussed in this forum many times before; use our Search function to search for "clone" in this forum and you'll find full explanations.

But in any case, to make clone() work for a class, that class has to do two things:

1) Override clone to call super.clone(); and

2) Implement the (empty) Cloneable interface.

Therefore, the minimal class on which you can actually call clone() looks like this:

As I said, why this is has been explained here many times before.

[Jess in Action][AskingGoodQuestions]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
It may seem weird that you need to override clone(), but the key is that you must give it public access to be able to call it from a different class. Protected methods are inherited by the subclass, but they aren't visible outside the class or subclass.
marc weber

Joined: Aug 31, 2004
Posts: 11343

For detailed explanation, see this appendix from Bruce Eckel's Thinking in Java...

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Jon Lee
Ranch Hand

Joined: Mar 04, 2005
Posts: 134
Thnx guys, now I have the answer.

I agree. Here's the link:
subject: clone method?
It's not a secret anymore!