Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I was wandering how can Object.Clone() access field fields that are actually defined in the subclasses, and not the actual implementation of this feature.

What is bothering me is that I cannot see the logic to allow base class (even if it is "special") to access the fields defined in the subclasses - doesn't this breaks whole object inheritance concept?

Consider this:

class Test implements Cloneable
{
    private String test_field;

    public Test()
    {
    }

    public Test clone() throws CloneNotSupportedException
    {
       return (Test)super.clone();
    }
}

Here, calling Test.clone() will copy the test_field also. Things are even getting weirder for me when it comes to the situation where Test is declared as an abstract class - calling clone() will allow me (in some way) to get the instance of the abstract class.

share|improve this question
1  
Did you look at the implementation of clone() in the JDK source? That would certainly show you how it's done. –  Nate W. Apr 5 '13 at 17:44
    
Sorry if I was unclear - I am not actually interested in the JDK's implementation - it is clear for me that there are dozens of ways to implement this. I was asking about the whole 'inheritance' thing. –  Nemanja Boric Apr 5 '13 at 17:47

1 Answer 1

up vote 3 down vote accepted

See this answer on SO http://stackoverflow.com/a/2326801/643483

The short answer to your question is yes, it is problematic to have the clone method on the Object class. According to Josh Bloch (via above link), it would have been better for the clone method to be defined on the Cloneable interface.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.