I'm having trouble understanding how to create and implement a copy constructor, as well as an overridden clone() method (not within the same class).
I know that for an "actual copy" you have to deep clone instead of simple clone (that took me a long time to figure out...). One of the more obvious solutions (to me) I found on here was to make a copy constructor.
For the sake of brevity, let's say I have a Dog object that holds two integers. In another class, Cat, I have a Cat object that consists of an array of 100 Dog objects (e.g., Dog[] cat = new Dog[100]). I've tried the following thus far:
// for a copy constructor public Cat(Cat cat) { Dog[] copy = new Dog[100]; for (int i = 0; i < 100; i++) { copy[i] = cat[i]; } } Something like that will always give me a type mismatch ("The type of expression must be array type but it resolved to Cat" and "Cannot convert from Cat to Dog"). It may be because it's 5AM where I am, but I just can't see why this doesn't work. Aren't copy and cat of the same type?
I get the same errors if I try to override with a clone() method of my own. I've never used clone() before (or seen it for that matter), so I'd like to see what I'm not understanding before trying to come up with my own. For what it's worth, though, I had the following commented out earlier and the compiler threw up on the return statement:
protected Cat clone() { Dog[] copy = new Dog[100]; int count = 0; (while (count < cat.length) { copy[count] = (Dog) cat[count]; count++; } return copy; } Same type mismatch error. Changing the header to "protected Dog[] clone()" made the compiler error go away, but clearly that didn't get me anywhere.
Thanks for any help!
catis an instance ofCatand notDog[].