Good morning, I would like to know what the Mutable Types in Java really are, since it is not very clear at times when it comes to teaching. Greetings
Good morning, I would like to know what the Mutable Types in Java really are, since it is not very clear at times when it comes to teaching. Greetings
The response from Ipman1971 is partially correct. A class is mutable when it allows to alter its state, that is, modify the values of the fields it contains, either by making its public fields or by providing methods that allow altering the values of the fields.
An immutable class not only does not provide methods that allow the modification of its state, but once an object of that class is initialized, its state can not be altered in any way. Any operation that results in an alteration of the state, what it actually does is to return a new object of the same class but with the modified state. To achieve this, the following conditions must be satisfied in the definition of the class:
final
modifier to the fields. final
). Here is an example of an immutable class that meets all these aspects in mind:
public class Inmutable {
//los primitivos son inmutables por defecto
private final int id;
//String es una clase inmutable
private final String nombre;
//List no se puede saber si es inmutable pero eso tiene arreglo
//la clase a almacenar en esta lista también debe ser inmutable
//sino Inmutable no sería del todo inmutable
private final List<BigDecimal> listaNumeros;
//En Java, la clase java.util.Date no es inmutable
//por ende, para trabajar con una fecha en una clase inmutable
//hay dos opciones: 1) Almacenar el long que representa al tiempo
//en lugar de almacenar Date. 2) Utilizar clases de un API que provee
//manejo de fechas para Java como Joda Time o Date and Time disponible
//desde Java 8 en el paquete java.time
//Para este caso, utilizaré la opción 1)
private final long fechaNacimiento;
//en el constructor se deben inicializar todos los campos
//ojo: se recibe un como parámetro
public Inmutable(int id, String nombre, List<BigDecimal> listaNumeros, Date fechaNacimiento) {
this.id = id;
this.nombre = nombre;
//para el caso de la lista, se decora para que sea inmutable
this.listaNumeros = Collections.unmodifiableList(listaNumeros);
//en el caso de Date, se almacena solo el valor entero
this.fechaNacimiento = fechaNacimiento.getTime();
}
//se crean getters para acceder a los campos
//se devuelve el primitivo puesto que no se puede modificar su valor
public int getId() {
return this.id;
}
//se devuelve la instancia directamente puesto que no se puede modificar su estado
public String getNombre() {
return this.nombre;
}
//se puede devolver esta lista puesto que ya es inmutable
//no hay problema si el cliente intenta modificarla
//se lanzara una excepción por el comportamiento de la lista
//devuelta por Collections#unmodifiableList
public List<BigDecimal> getListaNumeros() {
return this.listaNumeros;
}
//se devuelve una instancia de Date para el cliente de esta clase
//puesto que esta instancia de Date no está asociada a la clase
//no importa si el cliente modifica su estado
public Date getFechaNacimiento() {
return new Date(fechaNacimiento);
}
//se agregan dos operaciones
//una para agregar valores a la lista de numeros
//otro para "cambiar" la fecha de nacimiento
public Inmutable agregaNumero(BigDecimal numero) {
//preparamos la nueva lista a utilizar
List<BigDecimal> nuevaListaNumeros = new ArrayList<>(listaNumeros);
nuevaListaNumeros.add(numero);
//siempre se crea una nueva instancia a devolver
//de esta forma la instancia actual no altera su estado
return new Inmutable(id, nombre, nuevaListaNumeros, new Date(fechaNacimiento));
}
public Inmutable setFechaNacimiento(Date fechaNacimiento) {
return new Inmutable(id, nombre, listaNumeros, fechaNacimiento);
}
}
Well, I think you'll understand it quickly, a mutable object has properties that can change its value, for this the class has methods that allow the modification of properties.
And an immutable object is one that does not allow to modify its properties, they are assigned in its creation and can not be modified. I'll give you an example:
public class Mutable {
private int id;
Mutable(int id) {
this.id=id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id=id;
}
}
public class Inmutable {
//final cumple dos roles
//1. Forzar que se inicialize el campo 1 sola vez en la clase
// y que no se le pueda cambiar el valor
//2. Fuerza que el campo se inicie en el constructor de la clase
private final int id;
Inmutable(int id) {
this.id=id;
}
public int getId() {
return id;
}
}