I have a generic interface and I have to create a class to implement it. I thought at first this would work fine, putting it in the documentation that the interface requires a class that implements the clone method
genericClass<E extends Cloneable> implements genericInterface<E extends Cloneable>{
E data;
//code
public E get(){
return this.data.clone()
}
}
However this doesn't work in practice
package securedatacontainer;
public class Demo {
public static void main(String[] args) throws CloneNotSupportedException {
String s = "user";
A a = new A(5, s);
A b = a.clone();
System.out.println("a equals b: " +(a.equals(b)));
System.out.println("a == b: " + (a == b));
B<A> c = new B<>(a);
System.out.println("a equals c.data: " +(a.equals(c.data)));
System.out.println("a == c.data: " + (a == c.data));
A k = c.get();
System.out.println(k.value);
}
}
class A implements Cloneable{
int value;
String name;
public A(int x, String str ){
this.value = x;
this.name = str;
}
@Override
public A clone() throws CloneNotSupportedException {
A temp = new A(this.value, this.name);
return temp;
}
public boolean equals(A elem){
return (this.name).equals(elem.name) && this.value==elem.value;
}
}
class B <E extends Cloneable>{
E data;
public B(E elem){
this.data=elem;
}
public E get() throws CloneNotSupportedException{
return (E) this.data.clone();
}
}
I get
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.lang.Cloneable.clone
at securedatacontainer.B.get(Demo.java:60)
at securedatacontainer.Demo.main(Demo.java:19)
Because the project is supposed to be a data storage, I really doubt my teacher wants some shallow copy of the generic E element (note that is just a simple test program for clone, not the actual project). Can anyone tell me why this does not work or how I can make it work? I can't make any assumption about the input E element, only that it has its own clone() method