• Post Reply Bookmark Topic Watch Topic
  • New Topic

How does Object::clone know about the fields in the subclass objects that call it?  RSS feed

 
Steven Kissh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought that one concept in OOP was that parent classes don't know(need to know) anything about children classes. How can that be true if Object::clone returns an object that contains all the fields of the subclass when that subclass calls super.clone()?
 
Stephan van Hulst
Saloon Keeper
Posts: 7964
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Black voodoo magic.

No really.

There are two interfaces in the Java programming language that can be instantiated by performing native memory operations at a very low level: Cloneable and Serializable. You need to understand very well how they work, and try to avoid them in your own code.
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:Black voodoo magic.

No really.

This not far from the truth, really.

This is the code for the Object clone method (line number as seen GrepCode.com):

As you can see, the implementation is native, which means that it's written in the native (platform) code using JNI (Java Native Interface).  Also note that since Object does not implement the Cloneable interface, trying to call clone() on an Object will throw the CloneNotSupportException. You must declare your subclass as implementing the Cloneable interface if you want to be able to clone instances of it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!