How To create immutable class in java

This is one of the most asked interview question in java.

How To create immutable class in java.

  1. Declare the class as final so it can not be extended.
  2. Make all fields private so that direct access is not allowed.
  3. Do not provide setter methods for variables.
  4. Make all mutable fields final so that it’s value can be assigned only once.
  5. Initialize all the fields via a constructor.

here is example code

package test;

public final class ImmutableClassExampleMain {
    
public static void main(String[] args) {
              
ImmutableClassExample obj=new ImmutableClassExample(1, "vijay1");
System.out.println(obj);

}

}class ImmutableClassExample{
 
final private  int id;
final private  String name; 

public ImmutableClassExample(int id,String name){ 
    this.id=id;
    this.name=name;  
}
    
public String toString(){
    return "[id="+id+",name="+name+"]";
}
    
}
Advertisements
This entry was posted in Java. Bookmark the permalink.

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