Search code examples
javaclone

How to pass parameter in Object's clone function in Java


All:

I am wondering if I define a class implements Clonenble:

public class cloneobj implements Cloneable {
    String name;
    public cloneobj (String name){
        this.name = name;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }

}

I wonder how can I give name to new clone object?

Thanks


Solution

  • Make your clone method yourself:

    public Object clone() throws CloneNotSupportedException {
        return new cloneobj(name);
    }
    

    EDIT

    If you want to call super.clone();

    public Object clone() throws CloneNotSupportedException {
        cloneobj cloned = (cloneobj)super.clone();
        cloned.name=this.name; //maybe (String)this.name.clone(); could be used
        return cloned;
    }