How to pass a parameter to cloning function of an object in Java

All:

I am wondering if I define a class that 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 I can assign a name to the new clone object?

thank

+3


source to share


1 answer


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;
}

      

+2


source







All Articles