An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..
So how do you create an immutable object :
- Remove or make setters less accessible.
- Preveting methods from getting overriden.
- Make all fields final.
- Make defensive copies of mutable objects.
- Do not provide a clone method
- Do not provide a copy constructor
- return a fuctional object
public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}
public Complex add(Complex left , Complex right) {
// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}
The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat
No comments:
Post a Comment