Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

clone method?

 
Jon Lee
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jimmy Die
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.
 
Jon Lee
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FileName: CloneTest.java

 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For detailed explanation, see this appendix from Bruce Eckel's Thinking in Java...

http://www.faqs.org/docs/think_java/TIJ319.htm
 
Jon Lee
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thnx guys, now I have the answer.

Cheers
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic