Sunday, April 1, 2012

How to make a class immutable ??

Immutable class is a type of class whose object cant be modified after their creation, which means only constructor will be able to modify or write the fields values of the class.

Java :

In java best way to make a class as immutable is to declare all the fields or variables of the class as final, so declaring final, will prevent the variable or fields to be modified outside the constructor, it will also look after the memory synchronization.

 

Code Example :

class YourName implements Immutable {
private final String name, surname;

public YourName(String name, String surname) {
this.name = name;
this.surname = surname;
}

public String getname() {
return name;
}

public String getsurname() {
return surname;
}
}


 


C# :


In c# this can be done by making fields constant if nothing to be initialize at runtime , or through making set method as private,


Code example follows:


 


 

 // This class is immutable. After an object is created,
// it cannot be modified from outside the class. It uses a
// constructor to initialize its properties.
class YourName
{
// Read-only properties.
public string firstname{ get; private set; }
public string surname{ get; private set; }

// Public constructor.
public Contact(string fname, string sname)
{
firstname = fname;
surname = sname;
}
}


 


 


Some Videos available on this follows for better understanding :



No comments:

Post a Comment

Live

Your Ad Here