Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

oop - Accessing clone() from java.lang.Object

Here is something that I cannot understand.

In java.lang.Object the clone() is defined with protected modifier. By definition than it can be accessed by name inside its own class definition, by name inside any class derived from it, and by name in the definition of any class in the same package.

Here the Sample class is in another package, and obviously it can't access clone() from the Object class. But as Sample derives implicitly from Object, why is it not able to access it? The definition doesn't say that it HAS to satisfy both conditions (inside same package AND also to be a subclass).

public class Sample {

  public Object foo() throws CloneNotSupportedException {
   ... 
   return someObject.clone();
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your case, the clone() method is not visible because you are not calling it from a subclass. Sample derives from Object, so it can access its own clone() method, but not that of other objects.

Object clone() was designed with several mistakes. So it is not a good practice to use it - it is very hard to get it right:

  • the assumption is that not every object is clonable by default
  • if you override clone() making it public, it will still fail, because each class has to implement Cloneable
  • Cloneable, however, does not define any methods, so the users of the objects can't refer to it as Cloneable and expect a clone method.
  • every class in a hierarchy must call super.clone() for the default cloning mechanism to work

Check this question for alternatives.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...