Scenario 1:
class Mango{
final int marker = 10;
}
In a class, when you declare a variable as final and initialize it during declaration, that means you do not want to modify it from anywhere.
In that case, all of the created objects of the class maintained a similar value for this variable.
On the other hand, whenever we declare a variable as static, then at the class level a single variable is created which is shared with the objects. Any change in that static variable reflects to the other objects operations.
But actually, at points 1 and 2 we want to achieve point 3's behavior implicitly.
So, java force or suggest you create only one copy of the marker
variable by declaring is static
also.
class Mango{
final static int marker = 10;
}
Which is memory efficient, cleaner, and non-ambiguous.
Scenario 2:
public class Mango {
final int marker;
Mango(int m){
marker = m;
}
}
This type of declaration is totally different. In that case, every instance of the Mango
class has its own marker
variable, and it can be initialized only one time.
The first type of declaration ensures class-level final behavior and the second type of declaration ensures the object-level final behavior.