I was going through this question Why would one declare an immutable class final in Java?
I understood this Answer but need a code example.
I wrote it but has some doubts and would appreciate if someone can help.
public class Immutable {
private final int value;
public Immutable(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean equals(Object obj) {
return (obj instanceof Immutable
&& getValue() == ((Immutable) obj).getValue());
}
public int hashCode() {
int hash = 1;
hash = hash * 31 + value;
return hash;
}
}
public class Mutable extends Immutable {
private int realValue;
public Mutable(int value) {
super(value);
realValue = value;
}
public int getValue() {
return realValue;
}
public void setValue(int newValue) {
realValue = newValue;
}
}
// test class main()
Mutable key = new Mutable(30);
Hashtable<Immutable, String> ht = new Hashtable<Immutable,String>();
ht.put(new Immutable(10), "10");
ht.put(new Immutable(20), "20");
ht.put(key, "30");
System.out.println("Hashcode : "+key.hashCode()+", \tKey : "+key.getValue()+" => Value : "+ht.get(key));
key.setValue(40);
System.out.println("Hashcode : "+key.hashCode()+", \tKey : "+key.getValue()+" => Value : "+ht.get(key));
Output :
Hashcode : 61, Key : 30 => Value : 30
Hashcode : 61, Key : 40 => Value : 30
I can't relate the Answer given with this Code.