3

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.

Abizern
  • 146,289
  • 39
  • 203
  • 257
Eyal
  • 55
  • 1
  • 6

2 Answers2

7

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

Community
  • 1
  • 1
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • so as I understand, there is no cleaner solution than re-defining clone() (or newI as I called it) in my Interface, because Interfaces do not inherit from Object. – Eyal Nov 20 '09 at 12:03
  • Yes - it's been my experience that a lot of people stay clear of `clone()` because it is so non-standard. – oxbow_lakes Nov 20 '09 at 15:36
2

What would happen if you changed:

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

to

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

?

Stuart
  • 176
  • 2
  • no need. i is of type I. and the outer cast is needed because clone returns an Object type – Eyal Nov 20 '09 at 12:04