Frank Sposaro MSFT Frank Sposaro MSFT - 4 months ago 21
Android Question

Declare final variable, but set later

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

Answer

You can set a final variable only in a constructor or in an initializer. Regular methods cannot change the value of variables declared final.