How to create Java constants?

Asked

Viewed 340 times

2

A java constant cannot be changed, but can be assigned an initial value via another variable ?

For example, if we have in our program a method that hypothetically calculates the import rate of a product through its location and returns a value double, however this value cannot be changed in the course of the program, it must remain equal to the value initially returned in order to be applied elsewhere in several possible ways.

So, can I assign the value it returned to a constant? What are the ways to "unchange" a value that was calculated from another(s)?

1 answer

2


Java has no constants, but it’s not what you want. Java has read-only variables, or as it likes to call that its value is finished, so it can be put into the variable during the construction of the object, after which it can no longer be changed. This is how it’s done:

public final BigDecimal taxa;

I put in the Github for future reference.

The secret there is the final which does not allow the variable to be changed, except within the constructor.

I used BigDecimal because if it is a value that will be used for monetary calculation probably need accuracy, thing that the double can’t.

If you want a greater control and allow to change under certain circumstances there is no way. The solution would be the use of a method Setter that analyses whether or not it can change and makes the change or not, or not yet have such a method and only internally it make a change decision in some case, but never invoked directly by the consumer of the class with the intention of merely changing its value. This is a case that may be necessary if you only know the value after the built object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.