Immutable class is the class whose value cannot be changed throughout the life cycle.
Ex:String
We cannot change the content of String class, everytime new reference is created when we change the content.
To create custom immutable class in java
- Class should be made final so that no class can extend it.
- Declare all variables as final
- Provide constructors to set the values
- There should not be any public set method which can change the state of the object.
- provde getter method
package java9r.blogspot.com;
final class Person {
final int age;
final String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
public class PersonDetails {
public static void main(String[] args) {
Person p = new Person(22, "ravi");
System.out.println(p.age);
System.out.println(p.name);
}
}
OutPut
0 comments:
Post a Comment