In Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private and final, the difference is the static attribute.
What's better? And why?
In Java, what's the difference between:
private final static int NUMBER = 10;
and
private final int NUMBER = 10;
Both are private and final, the difference is the static attribute.
What's better? And why?
Final: Once a final variable has been assigned, it always contains the same value. wherever the variable is static or not static: it will be only one variable for all instances initialized one time in Memory
"Static" keyword makes the variable property of the class rather than individual instances of the class. There will be one copy of that variable that is shared amongst all the instances of that class. Any change in the state of the static variable will be reflected across all the instances. Add final to static and we get a variable that has been initialised once and for all at the class loading time and cannot be changed later by any instance of the class. Static final variables need to be initialised at the declaration time else we have compile time error. As far as private instance field is concerned, it refers to the property /state of an object /instance of a class. Each instance /object of the class will have its own copy of instance variable. When instance variable is declared final, it means we cannot change its value for this instance. For this we need to initialise the final variable either at declaration or in the constructor.If its not done in either of them, compile time error will show. Once initialised, if you try to reassign a value you will get a compile time error. Use static final variables where the data will be shared across all the instances of the class and you want the data to be read only.Use instance final variable if you want to represent some data that belongs to a each individual instance of the class but once stored cannot be changed. Usage of static and instance key word depends upon your design needs and what that data represents in the domain. If the data is used across the class instances then there is no need for individual copies/memory references for each object.