You will need to understand what is immutable type in java. Once you have created an immutable type object you can update or modify it. Below example show how immutable object is going to implement and how mutable object type is going to be implemented.

public class Immutable {
    public int x;
    Immutable(int x ){
        this.x = x;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }
}

class Mutable{
    public int x;

    public Mutable(int x) {
        this.x = x;
    }
}

class TestImmutable{
    public static void main(String[] args) {
        Immutable y = new Immutable(2);
        y.setX(5);
        System.out.println(y.hashCode());
        y.setX(6);
        System.out.println(y.hashCode());
        System.out.println(" YOU CAN SEE THAT HASH CODES ARE EQUAL EVEN THOUGH WE HAVE MODIFIED THE OBJECT");
    }
}

class TestMutable{
    public static void main(String[] args) {
        Mutable mutable = new Mutable(5);
        System.out.println(mutable.hashCode());
        mutable = new Mutable(4);
        System.out.println(mutable.hashCode());
        System.out.println(" YOU CAN SEE THAT HASH CODES ARE NOT EQUAL AND WE HAD TO CREATE OR RE INITIALIZED THE OBJECT SINCE WE DO HAVE SETTERS. ");
    }
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *

WP Facebook Auto Publish Powered By : XYZScripts.com