I know this is fairly simple topic, but I really want to wrap my head around it.
This is what I'm trying to do, but it doesn't like the final modifier. Is there another way to achieve the effect I'm looking for? Which is basically that I want to make sure the id can not change durning the Activities entire life.
private final long mId; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mId = getIntent().getLongExtra(ID_KEY, -1); }
I should point out that this is Android code. Thanks for all the help. I'm not worried about getters or setters or anyone changing my code. The reason I asked was to future proof my code for the next developer to take over. I found this post that also helps shed some light. Android - Activity Constructor vs onCreate
If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
Once we declare a variable with the final keyword, we can't change its value again. If we attempt to change the value of the final variable, then we will get a compilation error. Generally, we can consider a final variable as a constant, as the final variable acts like a constant whose values cannot be changed.
You can initialize final instance variables before constructor completes. A blank final instance variable must be definitely assigned at the end of every constructor of the class in which it is declared; otherwise a compile-time error occurs.
In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.
You can set a final
variable only in a constructor or in an initializer. Regular methods cannot change the value of variables declared final
.
You can't. But you can guarantee no external object changes it if it's private and you don't have a setter for it.
Alternatively, you can wrap the long value in another class - LazyImmutableLong
. But this is a more verbose approach, and you probably don't need it (note: the class below is not thread-safe)
class LazyImmutableLong { private Long value; public void setValue(long value) { if (this.value != null) { return; // the value has already been set } this.value = value; } public long getValue() {return value;} }
And in your activity
private LazyImmutableLong id = new LazyImmutableLong(); public void onCreate(..) { id.setValue(..); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With