In java, constants as known as keyword (final) with a value that will never change. I have seen some people create constants without declaring a static modifier. My question is, should constants be declared as a static? If so or if not, why?
If you assign a value to the final
variable when declaring it, there's no point in it not being static
, since each instance would have its own variable having the same value, which is wasteful.
However, if you need an instance variable whose value can only be set once (but different instances may have different values), that variable would have to be final
but not static
.
For example :
class Person
{
final int id;
public Person(int id) {
this.id = id;
}
}
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