java - question about final and static [duplicate]

0

Can you explain what is done or what happens in the following instruction:

private static final SecureRandom numerosAleatorios = new SecureRandom () ;

my doubt, how can an object be constant (final)? Static in the creation of an object?

    
asked by Marcos Ricra Cornejo 27.07.2018 в 04:06
source

2 answers

1

In java the reserved word static indicates that the varoles will be kept in memory during the execution of the application. The reserved word final indicates that the values can not be modified after its creation or assignment.

In java you can declare the constant and assign it later, however if you try to reassign the variable ( static final ) java will not allow it.

public class{
  private static final int CONSTANTE;

  public class(){
    CONSTANTE = 12345678;
    this.metodo();
  }

  private void metodo(){
    CONSTANTE = 98765; // esta asignación no es permitida y genera error
  }
}
    
answered by 27.07.2018 в 04:29
0

An attribute declared as static can be accessed or invoked without the need to instantiate an object of the class, so it is also sometimes referred to as a class variable since all objects share the same value which is maintained throughout the execution of the program.

On the other hand, an attribute declared as final indicates that only one value or object can be assigned to it once, and therefore its value will always be the same during the execution of the program, and if it is tried to change it would mark error.

Here is an example where the code is explained in the comments.

public class Constantes {
public static final double pi = 3.1416;
}

public class Main {
public static void main(args[]){
System.out.println("El valor de pi es" + Constantes.pi); ///Podemos acceder a la variable solamente escribiendo el nombre de la clase, y sin tener que crear un objeto de la clase Constates.
Constantes.pi = 34.13; /// nos marcaría error ya que su valor no puede cambiarse.
}
}
    
answered by 27.07.2018 в 05:02