Sunday, August 1, 2010

Immutable Object

Java has two Immutable classes - String and BigDecimal

Properties of Immutable java object -
1. Class as final so that no method can be overridden to provide mutable behavior to class.

2. All fields final and private

3. No setter or mutable methods

4. Normal getter methods

5. constructor to create the object of this class and that all fields should be passed as arguments.

public class MyImmutableClass{
private final String name;
private final int number;

public MyImmutableClass(String name, int number){
this.name=name;
this.number=number;
}

public int getNumber(){
return number;
}

public String getName(){
retutn name;
}
}

No comments:

Post a Comment