October 11, 2018

Example for an immutable class in java

/**
 *  Example for immutable class
 *  setting class as final implies that the class cannot be extended
 */
package com.belazy.algorithm;

/**
 * @author vinod aravind
 *
 */
public final class Employee {

private final String firstName;
private final String lastName;

public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
   
public String getFirstName(){
return firstName;
}

public String getLastName(){
return lastName;
}


}


Make the class as final - means class should not be extended
member variables as private final - means the value should not be changed

Final keyword in java

The value of  final variables could not be changed, But it can be initialized  through a constructor once

The final methods could not be override

The final class could not be extended

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments