Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

Can anyone tell me the difference between Mutable and Immutable objects for example?

1 Answer

0 votes
by (13.1k points)

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);

}

}

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
2 answers
asked Feb 18, 2021 in Java by Harsh (1.5k points)
0 votes
1 answer
asked Mar 31, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 7, 2021 in Python by ashely (50.2k points)
0 votes
1 answer

Browse Categories

...