its easier to explain in code so here
Object anObj;
anObj = new MyObj();
anObj = new Rectangle();
anObj.clone();//this doesnt exist because its on the root Object class
what can i use instead of the Object.clone() method in this example?
----------------------- extra info ------------------------------
I have added extra info but it seems to have gone in the middle of all the answers, so here it is again so it can be read.
Hi all these are all really helpful on topic of cloning or copying, which i now need to think about. but they dont help with the initial question. maybe more info from me will help you understand what im after.
I am overriding the clone for each of my objects and adding all the other clone and copy methods needed to completely clone the object, this includes adding a custom method to copy a bufferedimage. ie:-
public Object clone() {//i copied from 'thelost's answer
try {
CloningExample copy = (CloningExample)super.clone();
copy.names = (LinkedList)names.clone();
return copy;
} catch (CloneNotSupportedException e) {
return null;
}
}
but i have one variable in my class that is an Object but because it hold various other objects of different types, each of my types will have a clone method, but short of checking if its each of my types and then calling clone() on my type, which would be very long as i have many types, i cannot see how to copy or clone the object easily. is there a way os should i just write a static method like this?
static findTypeAndCopy(Object thisobj){
if(thisobj==null)
return null;
if(thisobj instanceOf MyObj1){
return ((MyObj1)thisobj).clone();
}else if(thisobj instanceOf MyObj2){
return ((MyObj2)thisobj).clone();
...
etc
}
???