I'm trying to study the difference between deep copy and shallow copy in Java. I created an example where I use a generic class OrganizedGroup to manage Enterprizes,Music groups and others. Then, I create a container with different groups of type OrganizedGroup.
import java.util.ArrayList;
interface Leader {
public void command();
}
class Singer implements Leader {
@Override
public void command() {
System.out.println("I'm a singer");
}
}
class Boss implements Leader {
@Override
public void command() {
System.out.println("I'm a boss");
}
}
class OrganizedGroup<T extends Leader> {
private T mandador;
public OrganizedGroup(T m) {
mandador = m;
}
public void posturaOficial() {
mandador.command();
}
public void setLeader(T m){
mandador = m;
}
}
class MusicGroup extends OrganizedGroup<Singer> {
public MusicGroup(Singer c) {
super(c);
}
public void playMusica() {
System.out.println("Playing music....");
}
}
class Enterprize extends OrganizedGroup<Boss> {
public Enterprize(Boss j) {
super(j);
}
public void makeDeal() {
System.out.println("Making a deal....");
}
}
public class Pruebas {
public static void main(String[] args) {
ArrayList<OrganizedGroup<? extends Leader>> go = new ArrayList();
OrganizedGroup<? extends Leader> g = new MusicGroup(new Singer());
go.add(g);
g = new Enterprize(new Boss());
go.add(g);
for (OrganizedGroup j : go) {
j.posturaOficial();
}
OrganizedGroup< ? extends Leader> t = go.get(0);
t.setLeader(new Singer()); //compile error
}
}
On the last line I try to modify the leader of the first group ( I need to do that in order to see the difference between shallow copy and deep copy (say I cloned go into go2)) however it gives the following compile error:
Singer cannot be converted to CAP#1 where CAP#1 is a fresh type-variable: CAP#1 extends Leader from capture of ? extends Leader
I need answer to solve this problem, not an explanation of the compile error but more importantly of what is conceptually wrong, what should be change and why.
Please,don't focus on bad design matters I actually made a different implementation of this (OrganizedGroup being abstract) but I need to solve this problem to practise with generics.