1
interface IBase {
    void doJob();
}

public class MyCache<T extends IBase> {
    private T t1;
    private T t2;
    public MyCache(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    }

    @PostConstruct
    private void init() {
        t1.update();
        t2 = t1.clone(); // ERROR!
    }
}

As you see, I'm trying to develop a generic class. In the function init(), I assign the copy of t1 to t2. But it can't be compiled.

I'm not very good at Java. Can someone help me on this issue?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 1
    You can't clone random objects. They'd need to implement Cloneable and expose the `clone()` method. But it's [better](https://stackoverflow.com/questions/2597965/why-people-are-so-afraid-of-using-clone-on-collection-and-jdk-classes) to add a copy constructor. – shmosel Oct 28 '22 at 18:29
  • "copy [constructor" is not applicable for an interface](https://stackoverflow.com/q/2804041/592355)...but you can just call it (& implement `default`) "method": `interface IBase { void doJob(); [default] IBase copyMe(IBase src)[;|{...}]}` – xerx593 Oct 29 '22 at 09:18

1 Answers1

1

Look at the contract public Object clone(), so to use this method in your class you shouild declare it and case Object to the T.

interface IBase extends Cloneable {

    void doJob();

    void update();
    
    Object clone();

}

public class MyCache<T extends IBase> {

    private T t1;
    private T t2;

    public MyCache(T t1, T t2) {
        this.t1 = t1;
        this.t2 = t2;
    }

    private void init() {
        t1.update();
        t2 = (T)t1.clone();
    }
}

P.S. This is working solution, but at this time an outdated. It's better to use a copy constructor instead.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35