Cloning a class

Asked

Viewed 112 times

1

I am "trying" to clone the following class:

public class CadHorario implements Serializable, Cloneable {

    private int cdHorario;
    ...
    private Date horarioInicio;
    private Date horarioFim;
    private DiasDaSemana diasDaSemana;
    ...

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Diasdasemana class:

public class DiasDaSemana implements Cloneable {

    private boolean seg;
    private boolean ter;
    private boolean qua;
    private boolean qui;
    private boolean sex;
    private boolean sab;
    private boolean dom;
    ...

    @Override
    protected Object clone() throws CloneNotSupportedException {
         return super.clone();
    }
}

some attribute is cloning, more others like DiasDaSemana is not cloning. I’m cloning like this:

CadHorario clonado = (CadHorario) horario.clone();

Could someone help me?

1 answer

0

Looking at what you’ve done, there’s nothing wrong. Just two remarks: I understand that it would not be necessary to implement the Cloneable interface in the Diasdasemana class as well; and by convention I would make the following adaptation in the clone method:

@Override
public CadHorario clone() throws CloneNotSupportedException {
   return (CadHorario) super.clone();
}

If any class attribute has not been cloned, it is probably because it has not been previously instantiated.

Finally, if you still can’t solve the problem you can use libraries like Beansutils (Apache Commons) or yourself implement a constructor for this, example:

public CadHorario(CadHorario horario){
   this.cHorario = horario.cHorario;
   ...
}

CadHorario clone = new CadHorario(horario);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.