Tuesday 1 May 2018

Immutable Class Example

package com.help4j.core;

import java.util.Date;

/**
 * Immutable class should mark as final so that it can not be extended by another 
class. 
 * Fields should mark as private so direct access is not allowed
 * Fields should mark as final so that value can not be modified once initialized
 **/

public final class MyImmutable {

    /**
     * String class is immutable
     **/

    private final String name;
    
    /**
     * Integer class is immutable
     **/

    private final Integer weight;
    
    /**
     * Date class is mutable
     **/

    private final Date dateOfBirth;
    
    /**
     * Default private constructor will ensure no unplanned construction of class
     * All the final fields are initialized through constructor
     */

    private MyImmutable(String name, Integer weight, Date dateOfBirth){
        this.name = name;
        this.weight = weight;
        this.dateOfBirth = new Date(dateOfBirth.getTime());
    }
    
    /**********************************************
     ***********PROVIDE NO SETTER METHODS *********
     **********************************************/
    
    /**
     * String class is immutable so we can return the instance variable as it is
     **/

    public String getName() {
        return name;
    }
    
    /**
     * Integer class is immutable so we can return the instance variable as it is
     **/

    public Integer getWeight() {
        return weight;
    }
    
    /**
     * Date class is mutable so we need a little care here.
     * We should not return the reference of original instance variable.
     * Instead a new Date object, with content copied to it, should be returned.
     **/

    public Date getDateOfBirth() {
        return new Date(dateOfBirth.getTime());
    }
}

No comments:

Post a Comment

Top CSS Interview Questions

These CSS interview questions are based on my personal interview experience. Likelihood of question being asked in the interview is from to...