Sometimes I see something like :
public class MainActivity extends Activity
{
public static final String url_google = "http://www.google.com";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
What I actually don’t get, is why using public static final , and not public final or final
I’m speaking very broadly, but if it’s final, you only need one instance of it anyways, so it saves memory by making it static.
To be more specific, the
finalkeyword means that whatever the variable stores cannot be changed. This means that once the variable has a value, you may use the variable, but you cannot modify it in any way. Commonly, to give a value to a final variable, you do so right from the declaration egfinal int variable = 12. As you can see I used an int for my example, however you can use anything, including reference variables. Reference variables, are special though, because you cannot change what the variable points to, but you can change the Object itself (such as using get/set methods).What this boils down to though, is that once you have made a final variable it occupies space in memory. Since we can’t modify this variable further, why should we recreate it every time our Class is instantiated? So we use the
statickeyword. This allows the variable to be created once, and only once in memory.There are though, some specific cases in which you would want to not use
staticand use just final. One example may be time sensitive variables, such as storing the time of Object instantiation.