I want to initialize a constant variable, which is 'final', but I also want to include it in the constructor of a class but I don't know if this is ok:
public class Avion
{
private final BigDecimal limiteAltura;
public Avion(String limiteAltura)
{
this.limiteAltura = new BigDecimal(limiteAltura);
}
}
The constructor is supposed to initialize a field with qualifying values. It is initialized with a String
which by default will be null
but it gives me the impression that it can be done in another way. A constant has to be initialized at the time of its declaration or in the constructor. What I want to achieve is to be explicit not to ignore code.
No, here you don't initialize it, here you declare it. It has the default value
null
, but you haven't initialized it.Your code is correct; as long as you only initialize it once (when declaring it or within each of the constructors) there is no problem.