Back
Can anyone tell me the difference between Mutable and Immutable objects for example?
Mutable objects have fields that can be changed, immutable object does not have fields can be changed after an object is created.
For Example:
class MutableClass { private int value; public MutableClass(int aValue) { value = aValue; } public void setValue(int aValue) { value = aValue; } public int getValue() { return value; }}class ImmutableClass { private final int value; // changed the constructor to say Immutable instead of mutable public ImmutableClass (final int aValue) { //The value is set. Now, and forever. value = aValue; } public final int getValue() { return value; }}public class Main{public static void main(String[] args) {MutableClass m=new MutableClass(10);ImmutableClass im=new ImmutableClass(15); }}
class MutableClass {
private int value;
public MutableClass(int aValue) {
value = aValue;
}
public void setValue(int aValue) {
public int getValue() {
return value;
class ImmutableClass {
private final int value;
// changed the constructor to say Immutable instead of mutable
public ImmutableClass (final int aValue) {
//The value is set. Now, and forever.
public final int getValue() {
public class Main
{
public static void main(String[] args) {
MutableClass m=new MutableClass(10);
ImmutableClass im=new ImmutableClass(15);
31k questions
32.8k answers
501 comments
693 users