jeudi 30 juillet 2015

How to set Immutablity to the class when reference of mutable class is present

public class ImmutabilityOfReferenceInstance {

    public static void main(String[] args) {

         MClass mc = new MClass();

         mc.setId(1);
         ImClass imc1 = new ImClass(mc);
         System.out.println("imc1 = "+imc1);

         mc.setId(2);
         ImClass imc2 = new ImClass(mc);
         System.out.println("imc2 = "+imc2);         

    }
}

final class ImClass {

    final private MClass mClass;

    public ImClass(MClass mClass) {
        this.mClass = mClass;
    }

    public MClass getmClass() {
        return mClass;
    }   

    @Override
    public String toString() {      
        return String.valueOf(mClass.getId());
    }

}


class MClass {
    private int id;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }   
}

I want to provide complete immutablity to the class IMClass, As we can see IMclass is immutable but it has an instance variable mclass that is the reference of MClass and MClass is a mutable class. I have tried changing the getter method getmClass() as below

public MClass getmClass() {
        return (MClass) mClass.clone();
    }

but it is not allowing me to do so, Could some one please correct it that where i am getting wrong. Thanks in advance

I have tried this but still getting the same result, values are getting updated
public class ImmutabilityOfReferenceInstance {

    public static void main(String[] args) {

         MClass mc = new MClass();

         mc.setId(1);
         ImClass imc1 = new ImClass(mc);
         System.out.println("imc1 = "+imc1);

         mc.setId(2);
         ImClass imc2 = new ImClass(mc);
         System.out.println("imc2 = "+imc2);         
    }
}

final class ImClass {

    final private MClass mClass;

    public ImClass(MClass mClass) {
        this.mClass = (MClass)mClass.clone();
    }

    public MClass getmClass() {
        return (MClass)mClass.clone();
    }   

    @Override
    public String toString() {      
        return String.valueOf(mClass.getId());
    }

}

class MClass implements Cloneable{
    private int id;


    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }   

    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire