Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...