Java Cloneable or copy constructor, why would I use any of those? What do either of those strategies actually do? [duplicate]

StackOverflow https://stackoverflow.com/questions/20770169

Domanda

The question I have is pretty noob like so please excuse me for my ignorance as I am a noob.

I came across code some consultants wrote in the company I work for. When I tried delving into the code, I had no idea why a class was implementing some interface called clonable. So I tried to google this clonable mess, and all I see is stuff like "don't use it" or "use copy constructor instead". I don't know what either of those things are. Could someone please elaborate the reasons for when this kind of cloning is actually needed? Why would I clone an object?

I spoke to the ex-consultant and he mentioned this would allow us to chain methods apparently. Like questionSet.dosomething().doAnotherThing().dowth();

public class QuestionSet implements Cloneable {
     ...

    /* (non-Javadoc)
     * @see java.lang.Object#clone()
     */
    @Override
    public QuestionSet clone() {
        return new QuestionSet(this);
    }

    ...
}
È stato utile?

Soluzione

It is used in situations where you pass an object to some other party. If the object is mutable and you do not want to risk that the other party changes your object you could give it just a clone or copy of your object instead of the original.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top