简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM