Search code examples
javaenumsclonepass-by-referencepass-by-value

Is it clone safe to pass a classes enum to a clone?


I have a simple class that holds skeleton for a much larger, bulkier class. All this skeleton is is a string id, a type enumeration and some flags for options.

I would like to be able to clone this skeleton, but I don't know if the enumeration is clone safe (pass by value). I think that they are not since they are treated like classes (pass by reference). Is it safe to just pass the enumeration into the clone?

Example for clarity:

class A {
    String id;
    Enum state;
    int flags;

    A clone() {
        A ret = new A();
        ret.id = id;
        ret.state = state; // Am I safe here?
        ret.flags = flags;
        return ret;
    }
}

Solution

  • An enum instance, by definition, is a singleton. There is only one instance of each enum instance, by design. So obviously, the only thing you can do is copy its reference.