How do I create a new instance from an old one?

306 views Asked by At

I have a circumstance where I need to create a new instance of a class from another instance of that class. It must be a new instance, rather than a reference to the old instance, because the new instance needs to be manipulated without effecting the old instance.

I have come to the conclusion that I must have a Constructor in my class, and in every class for every type used in that class, which takes its own type as a parameter, and creates new types from that parameter:

public class MainClass {
    public Type0 type0;
    public Type1 type1;
    public Type2 type2;


    MainClass(MainClass mc) {
        type0 = new Type0(mc.type0);
        type1 = new Type1(mc.type1);
        type2 = new Type2(mc.type2);
    }
}



public class Type0() {
    public int i;
    public SomeOtherType t;

    Type0(Type0 t0) {
        i = t0.i;
        t = new SomeOtherType(t0.t);
    }
}

 . . . 

This would all be so much easier in C++ where I could simply say newInstance = oldInstance. But in Java, what is the best practice for creating a new instance from an old instance? Is this what I will have to do? Is it best practice, in Java, to have these types of constructors in every class? Or is there a better way to go about this?

1

There are 1 answers

2
yts On BEST ANSWER

It not not advisable to use the clone method (in case someone suggests that).

You are correct that a good way to do it is by providing a copy constructor which takes in an instance to copy. This is what Joshua Bloch recommends in his popular book Effective Java.