2

I have this weird situation, where I have a class TheClass implementing interface TheInterface and class TheClass is supposed to have a copy() method with return type TheInterface, and it should make a shallow copy of itself. When trying to call my function copy() and use it, I get an Incompatible types error. I need to keep the return type of the copy() method as it is.

Is there some way how to do this?

Thank you

class TheClass implements TheInterface,Cloneable {


private Set<Integer> set;

public TheClass(){
    set=new HashSet<Integer>();
}

public TheInterface copy() {
    TheInterface clone = this.clone();
    return clone;
}

protected A clone(){
    A clone;
    try
    {
        clone = (A) super.clone();
    }
    catch (CloneNotSupportedException e)
    {
        throw new Error();
    }
    return clone;
}

here i get the incompatible types error

public class Main  {
public static void main(String[] args) {
    TheClass class1 = new TheClass();
    TheClass class2 = class1.copy();
petex7
  • 23
  • 3

1 Answers1

1

A partial improvement might be to make copy() in TheClass return TheClass, while the method in interface still returns TheInterface. This is allowed since return type is not part of Java's method signature.

This way, you could do

TheClass class1 = new TheClass();
TheClass class2 = class1.copy();

However, if you call copy() on a variable of (static) type TheInterface, you still have to assign it to TheInterface (but that seems logical):

TheInterface class1 = new TheClass();
TheInterface class2 = class1.copy(); // cannot be TheClass in this case
Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
  • With generics you could also defined the copy method so that any TheInterface implementation can be assigned, eg public T copy() { .. } – Andrew Gilmartin Oct 12 '18 at 20:55