Web Development

How to make a immutable class in Java

To make a class immutable, follow these five rules:

1. Don’t provide any methods that modify the object(known as mutators)
2. Ensure that no methods may be overridden. – Preventing method overrides is generally done by making the class final
3. Make all fields final
4. Make all fields private
5. Ensure exclusive access to any mutable components

Example of immutable class:

package com.study.effectivejava.secondchapter;

public final class Complex {
    private final float re;
    private final float im;
    public Complex(float re, float im){
        this.re = re;
        this.im = im;               
    public float realPart(){
        return re;
    public float imaginaryPart(){
        return im;
    public Complex add(Complex c){
        return new Complex(re + c.re, im + c.im);
    public Complex subtract(Complex c){
        return new Complex(re - c.re, im - c.im);
    public Complex multiply(Complex c){
        return new Complex(re * c.re - im * c.im, re * c.im + im * c.re);
    public Complex divide(Complex c){
        float tmp = c.re * c.re + c.im * c.im;
        return new Complex((re*c.re + im*c.im)/tmp, (im*c.re - re*c.im)/tmp);
    public boolean equals(Object o){
        if(o == this) return true;
        if(!(o instanceof Complex)) return false;
        Complex c = (Complex)o;
        return (Float.floatToIntBits(re) ==
                Float.floatToIntBits(c.re)) &&
    public int hashCode(){
        int result = 17 + Float.floatToIntBits(re);
        result = 37 * result + Float.floatToIntBits(im);
        return  result;
    public String toString(){
        return "(" + re + "+ " + im + "i)";

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s