,

Saturday, 1 July 2017

Immutable class in java 2 (Reference type)

If a class has a reference type variable , the content of it can be modified after creation of object.
It is necessary to take precaution and add proper code to avoid modification of reference type after creation of object.
In the below class , we have used reference type variable qualification of type ArrayList.

package com.immutable2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 
 * @author ganeshrashinker
 *
 */
// make the class final
public final class Employee {
// make the variables private and final
private final String name;
private final int age;
private final List<String> qualification;

// define the getters for the private variables
public String getName() {
return name;
}

public int getAge() {
return age;
}

public List<String> getQualification() {
// return qualification;
return qualification;
}

public Employee(String name, int age, List<String> qualification) {
super();
this.name = name;
this.age = age;
// Below line will allow modifying elements in list
// this.qualification = qualification;
                // Below line will not allow modifying elements in list
this.qualification = Collections.unmodifiableList(qualification);

}

@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + ", qualification=" + qualification + "]";
}


}

Collections.unmodifiableList(qualification) will not allow the user to modify the content of the qualification list.

package com.immutable2;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author ganeshrashinker
 *
 */
public class MainClass {

public static void main(String[] args) {
List<String> qualification = new ArrayList<>();
qualification.add("BA");
qualification.add("MA");
Employee emp = new Employee("John", 35, qualification);
//emp.getQualification().set(0, "DA");
System.out.println(emp);

}


}

Note: It is necessary to take precaution of reference type variables(objects) of the class and put additional restriction so that the content of the reference type variables cannot be modified.

No comments:

Post a comment