Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

clone

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

like image 341
Kuan Avatar asked Jul 14 '26 16:07

Kuan


1 Answers

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;
}
like image 170
maskacovnik Avatar answered Jul 19 '26 20:07

maskacovnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!