The word finalapplied to variables means that the value of the variable cannot be changed. This allows the compiler to ensure that the variable is only initialized on its declaration (in the case of class attributes, the variable must be assigned on declaration or in the class constructor). In case the variable is reset, this will throw a compile error.
For variables of primitive type, this is simple to understand:
final int i = 5;
i = 7; //error de compilación aquí
For variables of object type, consider that the value of the variable is a reference and not its state. Here an example:
public class MiEntidad {
int id;
String nombre;
}
//asignando una referencia como valor a la variable
final MiEntidad miEntidad = new MiEntidad();
//aquí se modifica el estado interno de dicha referencia
//pero la referencia mantiene su mismo valor
miEntidad.id = 1; //esto cambia el estado de l
miEntidad.nombre = "Luiggi";
//aquí se intenta asignar una nueva referencia a la variable
//por ende, ocurre un error de compilación
miEntidad = new MiEntidad();
Since a variable is declared as final, this assures the compiler that the variable cannot change its value. This is very useful when you have variables local to a method and these need to be used within a class local to the method (commonly called anonymous classes) since this class cannot assign values to variables that do not belong to the class or to local variables. Here an example:
public void metodoX() {
//si remueves la palabra final, saldrá un error de compilación
//en la clase interna
final int tope = 10;
Thread t = new Thread( () -> {
//esta es una clase interna local al método metodoX
//que implementa la interfaz Runnable
//y hace uso de la variable externa "tope"
//puesto que "tope" es ajena a la clase interna y
//no pertenece a la clase donde se encuentra metodoX
//la variable necesita ser declarada como final
for (int i = 1; i <= tope; i++) {
System.out.println(String.format("Hola %d", i));
}
});
t.start();
}
finalhas other uses:
Declare a class like final. This makes the class unable to be extended. Example:
public final class NoMeHereden {
}
//error de compilación
//puesto que la clase NoMeHereden está declarada como final
public class YoQuieroHeredarDe extends NoMeHereden {
}
Declare a method as final: The method cannot be overridden. Example:
public class HeredenDeMi {
public final void peroNoSobreescribanEsto() {
}
}
public class YoHeredoDe extends HeredenDeMi {
//error de compilación
//el método está declarado como final
//no puede ser sobreescrito
@Override
public void peroNoSobreescribanEsto() {
}
}
Define a class attribute as static final: The attribute has a constant value at compile and run time. This is mainly used to define constant variables at the application level. Example:
public class MisConstantes {
public static final int CERO = 0;
public static final String DELIMITADOR_BASE = "_";
//como es una constante, se debe asegurar que la variable
//y su estado no puedan ser modificados en tiempo de
//compilación
public static final List<String> EXTENSIONES_ACEPTADAS =
Collections.unmodifiableList(Arrays.asList("txt", "pdf", "csv"));
}
Additional: attributes defined in an interface are always declared as static final, that is, they are constants.
More official information (from the Java language specification) about it:
finalit has several uses, within the methods it is not only important to indicate that the variable cannot be modified... as @LuiggiMendoza already explained, it is also mandatory when you want to use one of these variables in an anonymous class...
ex:
int variable = 3;
Thread t = new Thread() { // clase anonima
public void run() {
System.out.println(variable); // <-- error de compilacion
}
};
t.start();
Now if you put the final modifier on
final int variable = 3;
Thread t = new Thread() { // clase anonima
public void run() {
System.out.println(variable); // OK
}
};
t.start();
The word
final
applied to variables means that the value of the variable cannot be changed. This allows the compiler to ensure that the variable is only initialized on its declaration (in the case of class attributes, the variable must be assigned on declaration or in the class constructor). In case the variable is reset, this will throw a compile error.For variables of primitive type, this is simple to understand:
For variables of object type, consider that the value of the variable is a reference and not its state. Here an example:
Since a variable is declared as
final
, this assures the compiler that the variable cannot change its value. This is very useful when you have variables local to a method and these need to be used within a class local to the method (commonly called anonymous classes) since this class cannot assign values to variables that do not belong to the class or to local variables. Here an example:final
has other uses:Declare a class like
final
. This makes the class unable to be extended. Example:Declare a method as
final
: The method cannot be overridden. Example:Define a class attribute as
static final
: The attribute has a constant value at compile and run time. This is mainly used to define constant variables at the application level. Example:Additional: attributes defined in an interface are always declared as
static final
, that is, they are constants.More official information (from the Java language specification) about it:
final
it has several uses, within the methods it is not only important to indicate that the variable cannot be modified... as @LuiggiMendoza already explained, it is also mandatory when you want to use one of these variables in an anonymous class...ex:
Now if you put the final modifier on