Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cloning interfaces in Java

Tags:

java

I have a problem in Java:

I have an interface:

public interface I extends Cloneable {

}

and an abstract class:

public abstract class AbstractClass {

    private I i;

    public I i() {
        return (I)(i).clone();
    }
}

but the usage of clone() yields the following error:

The method clone() is undefined for the type I

does anybody have any Idea how to get around this issue? the only fix I found is to add to I a new method: (I newI() ) that will clone I. is there a cleaner solution?

thanks.

like image 762
Eyal Avatar asked Jul 27 '26 16:07

Eyal


2 Answers

You need to override the clone() method to be public

public interface MyI extends Cloneable {
    public MyI clone();
}

Rather bizarrely, Cloneable does not actually contain the clone() method and clone() is protected on Object! It's been discussed before on SO

like image 104
oxbow_lakes Avatar answered Jul 30 '26 05:07

oxbow_lakes


What would happen if you changed:

return (I)(i).clone();

to

return ((I)i).clone();

?

like image 33
Stuart Avatar answered Jul 30 '26 04:07

Stuart



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!